- 约束handler入参和返回为func(ctx, req) (resp, error)。
- 通过反射,封装handler,在调用前后写入入参和返回的处理。
package testing
import (
"context"
"fmt"
"reflect"
"strings"
"testing"
)
type ReqParams struct {
Name string
Age int
}
type RouteHandlers struct{}
func (r *RouteHandlers) Test(c *context.Context, req *ReqParams) {
fmt.Println("req:", req)
}
type Router struct {
Method reflect.Value
Params reflect.Value
}
func TestReflact(t *testing.T) {
controller := &RouteHandlers{}
handlerRef := reflect.ValueOf(controller)
if handlerRef.NumMethod() == 0 {
return
}
hMap := make(map[string]map[string]Router)
structName := reflect.TypeOf(controller).String()
if strings.Contains(structName, ".") {
structName = structName[strings.Index(structName, ".")+1:]
}
if hMap[structName] == nil {
hMap[structName] = make(map[string]Router)
}
for i := 0; i < handlerRef.NumMethod(); i++ {
mCall := handlerRef.Method(i)
mName := handlerRef.Type().Method(i).Name
reqParams := reflect.New(mCall.Type().In(1).Elem())
hMap[structName][mName] = Router{
Method: mCall,
Params: reqParams,
}
}
fmt.Println(hMap)
c := context.TODO()
hMap[structName]["Test"].Method.Call([]reflect.Value{reflect.ValueOf(&c), hMap[structName]["Test"].Params})
}