Heys guys, I'm creating a library in golang for my company. I want the client pass to us a callback with func(t ) error; Since there's no generics in Go, I'm trying to check the arguments and return type through reflection.
But I'm failling right now. Any help?
func check(F interface{}) bool {
errorInterface := reflect.TypeOf((*error)(nil)).Elem()
if tpFunc := reflect.TypeOf(Func); tpFunc.Kind() != reflect.Func {
return false
} else if tpFunc.NumIn() != 1 || tpFunc.NumOut() != 1 {
return false
} else if tpArg := tpFunc.In(0); tpArg.Kind() != reflect.Ptr || tpArg.Elem().Kind() != reflect.Struct {
return false
} else if tpRet := tpFunc.Out(0); tpRet.Implements(errorInterface) {
return false
}
return true
}
type T0 struct {
A int64
B float
}
func F0(t *T0) error {
...
}
func F1(t *T0) int {
...
}
Fortunatelly my code actually works with syntax corrections, as pointed by @Cerise Limón. https://play.golang.org/p/nqooMtkoQ-
As @Kaedys asked, I'm calling the F function by reflection.
arg0 := reflect.New(tpArg.Elem()).Interface()
if err := json.Unmarshal(msg.Body, arg0); hadError(err) {
hadError(toErrorQueue(msg))
} else {
callback := reflect.ValueOf(Func)
args := []reflect.Value{reflect.ValueOf(arg0)}
if errInterface := callback.Call(args)[0].Interface(); errInterface != nil && hadError(errInterface.(error)) {
hadError(toErrorQueue(msg))
}
}