-
Notifications
You must be signed in to change notification settings - Fork 2
/
call.go
76 lines (65 loc) · 1.46 KB
/
call.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package fox
import (
"fmt"
"net/http"
"reflect"
"github.com/fox-gonic/fox/httperrors"
)
func call(ctx *Context, handler HandlerFunc) any {
var (
funcValue = reflect.ValueOf(handler)
funcType = funcValue.Type()
ctxValue = reflect.ValueOf(ctx)
)
// TODO(m) check handler type when route registering
if funcValue.Kind() != reflect.Func {
panic(fmt.Sprintf("%#v is not a function", handler))
}
var (
numIn = funcType.NumIn()
numOut = funcType.NumOut()
)
if numOut > 2 {
panic("only support handler func returns max is two values")
}
var values []reflect.Value
switch numIn {
case 0:
values = funcValue.Call([]reflect.Value{})
case 1:
values = funcValue.Call([]reflect.Value{ctxValue})
default:
in := make([]reflect.Value, 0, numIn)
in = append(in, ctxValue)
for i := 1; i < numIn; i++ {
// Bind handler params
parameter := reflect.New(funcType.In(i)).Interface()
if err := bind(ctx, parameter); err != nil {
msg := &httperrors.Error{
HTTPCode: http.StatusBadRequest,
Err: err,
Code: "BIND_ERROR",
}
return msg
}
in = append(in, reflect.ValueOf(parameter).Elem())
}
values = funcValue.Call(in)
}
switch numOut {
case 0:
return nil
case 1:
res := values[0].Interface()
if err, ok := res.(error); ok {
return err
}
return res
default: // 2
res, err := values[0].Interface(), values[1].Interface()
if err, ok := err.(error); ok {
return err
}
return res
}
}