forked from googollee/go-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
66 lines (61 loc) · 1.25 KB
/
handler.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
package socketio
import (
"fmt"
"reflect"
)
type funcHandler struct {
argTypes []reflect.Type
f reflect.Value
}
func newEventFunc(f interface{}) *funcHandler {
fv := reflect.ValueOf(f)
if fv.Kind() != reflect.Func {
panic("event handler must be a func.")
}
ft := fv.Type()
if ft.NumIn() < 1 || ft.In(0).Name() != "Conn" {
panic("handler function should be like func(socketio.Conn, ...)")
}
argTypes := make([]reflect.Type, ft.NumIn()-1)
for i := range argTypes {
argTypes[i] = ft.In(i + 1)
}
if len(argTypes) == 0 {
argTypes = nil
}
return &funcHandler{
argTypes: argTypes,
f: fv,
}
}
func newAckFunc(f interface{}) *funcHandler {
fv := reflect.ValueOf(f)
if fv.Kind() != reflect.Func {
panic("ack callback must be a func.")
}
ft := fv.Type()
argTypes := make([]reflect.Type, ft.NumIn())
for i := range argTypes {
argTypes[i] = ft.In(i)
}
if len(argTypes) == 0 {
argTypes = nil
}
return &funcHandler{
argTypes: argTypes,
f: fv,
}
}
func (h *funcHandler) Call(args []reflect.Value) (ret []reflect.Value, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("event call error: %s", r)
}
}
}()
ret = h.f.Call(args)
return
}