Skip to content

Commit

Permalink
support non-ptr interface (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
acoshift authored May 13, 2019
1 parent c019e52 commit 677216d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
20 changes: 14 additions & 6 deletions hrpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,15 @@ func (m *Manager) Handler(f interface{}) http.Handler {
}
}

var typ reflect.Type
var (
infType reflect.Type
infPtr bool
)
if i, ok := mapIn[miInterface]; ok {
typ = ft.In(i)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
infType = ft.In(i)
if infType.Kind() == reflect.Ptr {
infType = infType.Elem()
infPtr = true
}
}

Expand All @@ -142,7 +146,7 @@ func (m *Manager) Handler(f interface{}) http.Handler {
}
// inject request interface
if i, ok := mapIn[miInterface]; ok {
rfReq := reflect.New(typ)
rfReq := reflect.New(infType)
req := rfReq.Interface()
err := decoder(r, req)
if err != nil {
Expand All @@ -159,7 +163,11 @@ func (m *Manager) Handler(f interface{}) http.Handler {
}
}
}
vIn[i] = rfReq
if infPtr {
vIn[i] = rfReq
} else {
vIn[i] = rfReq.Elem()
}
}
// inject request
if i, ok := mapIn[miRequest]; ok {
Expand Down
15 changes: 15 additions & 0 deletions hrpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,21 @@ func TestHandler(t *testing.T) {
reset()
h.ServeHTTP(w, r)
mustSuccess()

// non-pointer struct request and response
h = m.Handler(func(req requestType) (res struct {
OK string `json:"ok"`
}, err error) {
if req.Data != 1 {
t.Fatalf("invalid data")
}
res.OK = "1"
return
})
r = httptest.NewRequest(http.MethodPost, "http://localhost", successBody)
reset()
h.ServeHTTP(w, r)
mustSuccess()
}

func TestDefault(t *testing.T) {
Expand Down

0 comments on commit 677216d

Please sign in to comment.