-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservemux.go
52 lines (45 loc) · 1011 Bytes
/
servemux.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 peanats
import (
"fmt"
"net/http"
"sync"
)
type muxEntry struct {
handler Handler
subject string
}
// ServeMux is a handler multiplexer
type ServeMux struct {
m map[string]muxEntry
once sync.Once
}
func (m *ServeMux) init() {
m.m = make(map[string]muxEntry)
}
func (m *ServeMux) Serve(pub Publisher, req Request) error {
m.once.Do(m.init)
entry, found := m.m[req.Subject()]
if !found {
return &Error{
Code: http.StatusNotFound,
Message: http.StatusText(http.StatusNotFound),
}
}
return entry.handler.Serve(pub, req)
}
func (m *ServeMux) Handle(f Handler, subjects ...string) error {
m.once.Do(m.init)
for i := range subjects {
if _, found := m.m[subjects[i]]; found {
return fmt.Errorf("duplicate subject: %q", subjects[i])
}
m.m[subjects[i]] = muxEntry{
handler: f,
subject: subjects[i],
}
}
return nil
}
func (m *ServeMux) HandleFunc(f func(Publisher, Request) error, subjects ...string) error {
return m.Handle(HandlerFunc(f), subjects...)
}