...
1 package emperror
2
3
4
5
6
7
8
9
10 func HandlerWith(handler Handler, keyvals ...interface{}) Handler {
11 if len(keyvals) == 0 {
12 return handler
13 }
14
15 kvs, handler := extractHandlerContext(handler)
16
17 kvs = append(kvs, keyvals...)
18
19 if len(kvs)%2 != 0 {
20 kvs = append(kvs, nil)
21 }
22
23
24
25
26 return newContextualHandler(handler, kvs[:len(kvs):len(kvs)])
27 }
28
29
30
31
32
33
34 func HandlerWithPrefix(handler Handler, keyvals ...interface{}) Handler {
35 if len(keyvals) == 0 {
36 return handler
37 }
38
39 prevkvs, handler := extractHandlerContext(handler)
40
41 n := len(prevkvs) + len(keyvals)
42 if len(keyvals)%2 != 0 {
43 n++
44 }
45
46 kvs := make([]interface{}, 0, n)
47 kvs = append(kvs, keyvals...)
48
49 if len(kvs)%2 != 0 {
50 kvs = append(kvs, nil)
51 }
52
53 kvs = append(kvs, prevkvs...)
54
55 return newContextualHandler(handler, kvs)
56 }
57
58
59 func extractHandlerContext(handler Handler) ([]interface{}, Handler) {
60 var kvs []interface{}
61
62 if c, ok := handler.(*contextualHandler); ok {
63 handler = c.handler
64 kvs = c.keyvals
65 }
66
67 return kvs, handler
68 }
69
70
71
72
73 type contextualHandler struct {
74 handler Handler
75 keyvals []interface{}
76 }
77
78
79 func newContextualHandler(handler Handler, kvs []interface{}) Handler {
80 chandler := &contextualHandler{
81 handler: handler,
82 keyvals: kvs,
83 }
84
85 return chandler
86 }
87
88
89 func (h *contextualHandler) Handle(err error) {
90 err = With(err, h.keyvals...)
91
92 h.handler.Handle(err)
93 }
94
View as plain text