forked from vmihailenco/taskq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
68 lines (54 loc) · 1.18 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
67
68
package msgqueue
import (
"fmt"
"reflect"
)
var errorType = reflect.TypeOf((*error)(nil)).Elem()
type Handler interface {
HandleMessage(msg *Message) error
}
type HandlerFunc func(*Message) error
func (fn HandlerFunc) HandleMessage(msg *Message) error {
return fn(msg)
}
type reflectFunc struct {
fv reflect.Value // Kind() == reflect.Func
ft reflect.Type
}
var _ Handler = (*reflectFunc)(nil)
func NewHandler(fn interface{}) Handler {
if fn == nil {
return nil
}
if h, ok := fn.(Handler); ok {
return h
}
h := reflectFunc{
fv: reflect.ValueOf(fn),
}
h.ft = h.fv.Type()
if h.ft.Kind() != reflect.Func {
panic(fmt.Sprintf("got %s, wanted %s", h.ft.Kind(), reflect.Func))
}
return &h
}
func (h *reflectFunc) HandleMessage(msg *Message) error {
body, err := msg.GetBody()
if err != nil {
return err
}
args, err := decodeArgs(body, h.ft)
if err != nil {
return err
}
if len(args) != h.ft.NumIn() {
return fmt.Errorf("got %d args, handler expects %d args", len(args), h.ft.NumIn())
}
out := h.fv.Call(args)
if n := h.ft.NumOut(); n > 0 && h.ft.Out(n-1) == errorType {
if errv := out[n-1]; !errv.IsNil() {
return errv.Interface().(error)
}
}
return nil
}