-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbefore.go
55 lines (46 loc) · 1.04 KB
/
before.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
package httpwrap
import "reflect"
type beforeFn struct {
val reflect.Value
inTypes []reflect.Type
outTypes []reflect.Type
}
func newBefore(fn any) (beforeFn, error) {
val := reflect.ValueOf(fn)
fnType := val.Type()
inTypes, outTypes := []reflect.Type{}, []reflect.Type{}
for i := 0; i < fnType.NumIn(); i++ {
inTypes = append(inTypes, fnType.In(i))
}
for i := 0; i < fnType.NumOut(); i++ {
outTypes = append(outTypes, fnType.Out(i))
}
if err := validateBefore(inTypes, outTypes); err != nil {
return beforeFn{}, err
}
return beforeFn{
val: val,
inTypes: inTypes,
outTypes: outTypes,
}, nil
}
func (fn beforeFn) run(ctx *runctx) error {
inputs, err := ctx.generate(fn.inTypes)
if err != nil {
return err
}
outs := fn.val.Call(inputs)
for i := 0; i < len(outs); i++ {
ctx.provide(outs[i].Interface())
}
if len(outs) == 0 {
return nil
} else if !isError(fn.outTypes[len(outs)-1]) {
return nil
}
lastVal := outs[len(outs)-1]
if lastVal.IsNil() {
return nil
}
return lastVal.Interface().(error)
}