-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_mux.go
53 lines (43 loc) · 986 Bytes
/
handler_mux.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
package cone
import "fmt"
func NewHandlerMux() *HandlerMux {
return &HandlerMux{handlers: make(map[string]Handler)}
}
type HandlerMux struct {
handlers map[string]Handler
}
func (h *HandlerMux) Handle(subject string, handler Handler) {
err := h.register(subject, handler)
if err != nil {
panic(err)
}
}
func (h *HandlerMux) HandleFunc(subject string, handlerFunc HandlerFunc) {
err := h.register(subject, handlerFunc)
if err != nil {
panic(err)
}
}
func (h *HandlerMux) register(subject string, handler Handler) error {
if subject == "" {
return fmt.Errorf("empty subject is not allowed")
}
h.handlers[subject] = handler
return nil
}
func (h *HandlerMux) Serve(r Response, e *Event) {
if e == nil {
panic("event is nil")
}
if err := h.serveEvent(r, e); err != nil {
panic(err)
}
}
func (h *HandlerMux) serveEvent(r Response, e *Event) error {
handler, ok := h.handlers[e.Subject]
if !ok {
return r.Nak()
}
handler.Serve(r, e)
return r.Ack()
}