bus: dont mix ctx/classic handlers

This commit is contained in:
bergquist
2018-06-10 23:17:18 +02:00
parent e2275701d8
commit 629eab0b1e
5 changed files with 17 additions and 41 deletions

View File

@@ -76,25 +76,13 @@ func (b *InProcBus) SetTransactionManager(tm TransactionManager) {
func (b *InProcBus) DispatchCtx(ctx context.Context, msg Msg) error {
var msgName = reflect.TypeOf(msg).Elem().Name()
// we prefer to use the handler that support context.Context
var handler = b.handlersWithCtx[msgName]
var withCtx = true
// fallback to use classic handlers
if handler == nil {
withCtx = false
handler = b.handlers[msgName]
}
if handler == nil {
return ErrHandlerNotFound
}
var params = []reflect.Value{}
if withCtx {
params = append(params, reflect.ValueOf(ctx))
}
params = append(params, reflect.ValueOf(ctx))
params = append(params, reflect.ValueOf(msg))
ret := reflect.ValueOf(handler).Call(params)

View File

@@ -33,22 +33,23 @@ func TestDispatchCtxCanUseNormalHandlers(t *testing.T) {
t.Errorf("expected bus to return HandlerNotFound is no handler is registered")
}
bus.AddHandler(handler)
bus.AddHandlerCtx(handlerWithCtx)
t.Run("when a normal handler is registered", func(t *testing.T) {
bus.AddHandler(handler)
bus.DispatchCtx(context.Background(), &testQuery{})
bus.Dispatch(&testQuery{})
if handlerCallCount != 1 {
t.Errorf("Expected normal handler to be called once")
t.Errorf("Expected normal handler to be called 1 time. was called %d", handlerCallCount)
}
})
t.Run("when a ctx handler is registered", func(t *testing.T) {
bus.AddHandlerCtx(handlerWithCtx)
bus.DispatchCtx(context.Background(), &testQuery{})
t.Run("when a ctx handler is registered", func(t *testing.T) {
bus.DispatchCtx(context.Background(), &testQuery{})
if handlerWithCtxCallCount != 1 {
t.Errorf("Expected ctx handler to be called once")
}
})
if handlerWithCtxCallCount != 1 {
t.Errorf("Expected ctx handler to be called 1 time. was called %d", handlerWithCtxCallCount)
}
})
}