Skip to content

Commit 4210c1d

Browse files
authored
Fix: Register() does not work properly for value type (#9)
1 parent 720e409 commit 4210c1d

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

mux.go

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package dew
22

33
import (
44
"context"
5+
"fmt"
56
"reflect"
67
"sync"
78
)
@@ -166,16 +167,24 @@ func (mx *mux) updateHandler(m middlewareType) {
166167
}
167168

168169
// Register adds the handler to the mux for the given command type.
169-
func (mx *mux) Register(handler any) {
170-
hdlTyp := reflect.TypeOf(handler)
171-
for i := 0; i < hdlTyp.NumMethod(); i++ {
172-
mtdTyp := hdlTyp.Method(i)
173-
if isHandlerMethod(mtdTyp) {
174-
cmdTyp := mtdTyp.Type.In(2).Elem()
175-
if cmdTyp.Implements(reflect.TypeOf((*Action)(nil)).Elem()) {
176-
mx.addHandler(cmdTyp, reflect.ValueOf(handler).Method(i).Interface())
177-
} else if cmdTyp.Implements(reflect.TypeOf((*QueryAction)(nil)).Elem()) {
178-
mx.addHandler(cmdTyp, reflect.ValueOf(handler).Method(i).Interface())
170+
func (mx *mux) Register(handler interface{}) {
171+
val := reflect.ValueOf(handler)
172+
typ := val.Type()
173+
174+
// Convert to pointer if not already
175+
if typ.Kind() != reflect.Ptr {
176+
val = reflect.New(typ)
177+
val.Elem().Set(reflect.ValueOf(handler))
178+
typ = val.Type()
179+
}
180+
181+
for i := 0; i < typ.NumMethod(); i++ {
182+
method := typ.Method(i)
183+
if isHandlerMethod(method) {
184+
cmdType := method.Type.In(2).Elem()
185+
if cmdType.Implements(reflect.TypeOf((*Action)(nil)).Elem()) ||
186+
cmdType.Implements(reflect.TypeOf((*QueryAction)(nil)).Elem()) {
187+
mx.addHandler(cmdType, val.Method(i).Interface())
179188
}
180189
}
181190
}
@@ -187,6 +196,7 @@ func (mx *mux) setupHandler() {
187196
mx.updateHandler(mQuery)
188197
}
189198
if mx.mHandlers[mDispatch] == nil {
199+
println("setupHandler")
190200
mx.updateHandler(mDispatch)
191201
}
192202
if mx.parent != nil {
@@ -195,6 +205,7 @@ func (mx *mux) setupHandler() {
195205
}
196206

197207
func (mx *mux) addHandler(t reflect.Type, h any) {
208+
println(fmt.Sprintf("addHandler: %v", t))
198209
mx.entries.Store(t, &handler{handler: h, mux: mx})
199210
}
200211

mux_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ func TestMux_BasicCommand(t *testing.T) {
2929
}
3030
}
3131

32+
func TestMux_ValueTypeHandler(t *testing.T) {
33+
var userHandler userHandler
34+
35+
mux := dew.New()
36+
mux.Register(userHandler)
37+
38+
createUser := &createUser{Name: "john"}
39+
testRunDispatch(t, dew.NewAction(mux, createUser))
40+
if createUser.Result != "user created" {
41+
t.Fatalf("unexpected result: %s", createUser.Result)
42+
}
43+
}
44+
3245
func TestMux_HandlerNotFound(t *testing.T) {
3346
defer func() {
3447
if r := recover(); r == nil {

0 commit comments

Comments
 (0)