MakeHttpApiReceiverByValue 추가

This commit is contained in:
2023-09-05 11:56:53 +09:00
parent 84f56dfc50
commit 5117847740

View File

@ -613,6 +613,49 @@ type HttpApiReceiver struct {
methods map[string]apiFuncType
}
func MakeHttpApiReceiverByValue(receiver reflect.Value) HttpApiReceiver {
methods := make(map[string]apiFuncType)
tp := receiver.Type()
name := tp.Elem().Name()
for i := 0; i < tp.NumMethod(); i++ {
method := tp.Method(i)
if method.Type.NumIn() != 3 {
continue
}
if method.Type.In(0) != tp {
continue
}
var w http.ResponseWriter
if method.Type.In(1) != reflect.TypeOf(w) {
continue
}
var r http.Request
if method.Type.In(2) != reflect.TypeOf(&r) {
continue
}
if method.Name == "ServeHTTP" {
continue
}
funcptr := method.Func.Pointer()
p1 := unsafe.Pointer(&funcptr)
p2 := unsafe.Pointer(&p1)
testfunc := (*func(*T, http.ResponseWriter, *http.Request))(p2)
methods[name+"."+method.Name] = func(w http.ResponseWriter, r *http.Request) {
(*testfunc)(receiver.Interface(), w, r)
}
}
return HttpApiReceiver{
methods: methods,
}
}
func MakeHttpApiReceiver[T any](receiver *T) HttpApiReceiver {
methods := make(map[string]apiFuncType)