-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
52 lines (44 loc) · 981 Bytes
/
main.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
package httpwrap
import (
"reflect"
)
type mainFn struct {
val reflect.Value
inTypes []reflect.Type
outTypes []reflect.Type
}
func newMain(fn any) (mainFn, 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 := validateMain(inTypes, outTypes); err != nil {
return mainFn{}, err
}
return mainFn{
val: val,
inTypes: inTypes,
outTypes: outTypes,
}, nil
}
func (fn mainFn) run(ctx *runctx) any {
inputs, err := ctx.generate(fn.inTypes)
if err != nil {
return nil
}
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 len(outs) == 1 && isError(fn.outTypes[0]) {
return nil
}
return outs[0].Interface()
}