-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.go
executable file
·128 lines (101 loc) · 2.36 KB
/
dispatcher.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package scaffold
import (
"net/http"
"sync"
"golang.org/x/net/context"
)
// Dispatcher dipatches requests to routes
type Dispatcher interface {
http.Handler
Handler
Handle(route Route, handlers ...Handler)
Middleware(route Route, middleware ...Middleware)
NotFoundHandler(route Route, handler Handler)
}
type dispatcher struct {
lock sync.RWMutex
*node
hosts map[string]*node
}
// DefaultDispatcher implements dispatcher allowing for basic url params
func DefaultDispatcher() Dispatcher {
return &dispatcher{
node: newNode(0),
hosts: make(map[string]*node),
}
}
func (d *dispatcher) NotFoundHandler(route Route, handler Handler) {
method := route.Method
parts := pathSplit(route.Pattern)
if len(route.Hosts) != 0 {
for _, host := range route.Hosts {
d.host(host).error(method, parts, handler)
}
return
}
d.error(method, parts, handler)
}
func (d *dispatcher) Middleware(route Route, middleware ...Middleware) {
if len(middleware) == 0 {
return
}
method := route.Method
parts := pathSplit(route.Pattern)
if len(route.Hosts) != 0 {
for _, host := range route.Hosts {
d.host(host).use(method, parts, middleware...)
}
return
}
d.use(method, parts, middleware...)
}
func (d *dispatcher) Handle(route Route, handlers ...Handler) {
if len(handlers) == 0 {
return
}
method := route.Method
parts := pathSplit(route.Pattern)
if len(route.Hosts) != 0 {
for _, host := range route.Hosts {
d.host(host).handle(method, parts, handlers...)
}
return
}
d.handle(method, parts, handlers...)
}
func (d *dispatcher) CtxServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx, parts := URLParts(ctx, r)
var h1, h2 Handler
var m1, m2 []Middleware
if host, ok := d.hosts[r.URL.Host]; ok {
h1, m1, _ = host.resolve(r.Method, parts)
}
h2, m2, _ = d.resolve(r.Method, parts)
h := d.notFoundHandler(r.Method, h1, h2)
if h == nil {
h = NotFoundHandler
}
for i := range m1 {
h = m1[len(m1)-1-i](h)
}
for i := range m2 {
h = m2[len(m2)-1-i](h)
}
h.CtxServeHTTP(ctx, w, r)
}
func (d *dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
d.CtxServeHTTP(ctx, w, r)
}
func (d *dispatcher) host(host string) *node {
d.lock.RLock()
if n, ok := d.hosts[host]; ok {
return n
}
d.lock.RUnlock()
d.lock.Lock()
n := newNode(0)
d.hosts[host] = n
d.lock.Unlock()
return n
}