/
router.go
237 lines (216 loc) · 5.22 KB
/
router.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package hostrouter
import (
"net/http"
"strings"
"github.com/prasannavl/go-gluons/http/handlerutils"
"github.com/prasannavl/mchain/hconv"
"github.com/gobwas/glob"
"github.com/prasannavl/go-gluons/log"
"github.com/prasannavl/mchain"
)
type HostRouter struct {
Items interface{}
Threshold int
PatternItems []RouterGlobItem
NotFound mchain.Handler
HostFunc func(*http.Request) string
}
type RouterItem struct {
host string
handler mchain.Handler
}
type RouterGlobItem struct {
pattern string
matcher glob.Glob
handler mchain.Handler
}
func New() *HostRouter {
return &HostRouter{
Threshold: 7,
NotFound: handlerutils.NotFoundHandler(),
HostFunc: LowerCasedHostFromHeader,
}
}
func LowerCasedHostFromHeader(r *http.Request) string {
hostname := stripPort(r.Host)
return strings.ToLower(hostname)
}
func stripPort(hostport string) string {
colon := strings.IndexByte(hostport, ':')
if colon == -1 {
return hostport
}
if i := strings.IndexByte(hostport, ']'); i != -1 {
return strings.TrimPrefix(hostport[:i], "[")
}
return hostport[:colon]
}
func (h *HostRouter) checkVariants() {
if h.HostFunc == nil {
panic("HostFunc cannot be nil")
}
if h.NotFound == nil {
panic("NotFound handler cannot be nil. Note: NopHandler can be used if that's the desired behavior")
}
}
func (h *HostRouter) Build() mchain.Handler {
h.checkVariants()
if items, ok := h.Items.(map[string]mchain.Handler); ok {
hh := func(w http.ResponseWriter, r *http.Request) error {
hostname := h.HostFunc(r)
if handler, ok := items[hostname]; ok {
log.Trace("host-router: host: " + hostname)
return handler.ServeHTTP(w, r)
}
for _, x := range h.PatternItems {
if x.matcher.Match(hostname) {
log.Trace("host-router: match: - " + hostname + " pattern: " + x.pattern)
return x.handler.ServeHTTP(w, r)
}
}
return h.NotFound.ServeHTTP(w, r)
}
return mchain.HandlerFunc(hh)
}
items := h.Items.([]RouterItem)
hx := func(w http.ResponseWriter, r *http.Request) error {
hostname := h.HostFunc(r)
for _, x := range items {
if x.host == hostname {
log.Trace("host-router: host: " + hostname)
return x.handler.ServeHTTP(w, r)
}
}
for _, x := range h.PatternItems {
if x.matcher.Match(hostname) {
log.Trace("host-router: match: - " + hostname + " pattern: " + x.pattern)
return x.handler.ServeHTTP(w, r)
}
}
return h.NotFound.ServeHTTP(w, r)
}
return mchain.HandlerFunc(hx)
}
func (h *HostRouter) BuildHttp(errorHandler mchain.ErrorHandler) http.Handler {
return hconv.ToHttp(h.Build(), errorHandler)
}
func (h *HostRouter) resolveContainer() {
switch item := h.Items.(type) {
case map[string]mchain.Handler:
if len(item) < h.Threshold+1 {
s := make([]RouterItem, 0, len(item)+1)
for k, v := range item {
s = append(s, RouterItem{host: k, handler: v})
}
h.Items = s
}
case []RouterItem:
if len(item)+1 > h.Threshold {
m := make(map[string]mchain.Handler, len(item)+1)
for _, x := range item {
m[x.host] = x.handler
}
h.Items = m
}
default:
h.Items = []RouterItem{}
}
}
func (h *HostRouter) HandleHost(host string, handler mchain.Handler) {
h.resolveContainer()
switch item := h.Items.(type) {
case map[string]mchain.Handler:
if handler == nil {
delete(item, host)
} else {
item[host] = handler
}
case []RouterItem:
if handler == nil {
for i, x := range item {
if x.host == host {
// Remove item
h.Items = append(item[:i], item[i+1:]...)
break
}
}
} else {
route := RouterItem{host, handler}
for i, x := range item {
if x.host == host {
// Replace item
item[i] = route
return
}
}
h.Items = append(item, route)
}
}
}
func (h *HostRouter) HandlePattern(globPattern string, handler mchain.Handler) {
hasStar := false
for _, x := range globPattern {
if x == '*' {
hasStar = true
break
}
}
if !hasStar {
h.HandleHost(globPattern, handler)
return
}
items := h.PatternItems
// note: ok to copy into x during range
for i, x := range items {
if x.pattern == globPattern {
if handler == nil {
h.PatternItems = append(items[:i], items[i+1:]...)
return
}
items[i].handler = handler
return
}
}
h.PatternItems = append(items, RouterGlobItem{
pattern: globPattern, matcher: glob.MustCompile(globPattern), handler: handler})
}
func (h *HostRouter) Clone() *HostRouter {
return &HostRouter{
Items: h.cloneItems(),
Threshold: h.Threshold,
PatternItems: h.clonePatternItems(),
}
}
func (h *HostRouter) cloneItems() interface{} {
if items, ok := h.Items.(map[string]http.Handler); ok {
newMap := make(map[string]http.Handler, len(items))
if len(items) < 1 {
return nil
}
for k, v := range items {
newMap[k] = v
}
return newMap
} else if items, ok := h.Items.([]RouterItem); ok {
if len(items) < 1 {
return nil
}
newSlice := make([]RouterItem, len(items))
for i, v := range items {
newSlice[i] = v
}
return newSlice
}
return nil
}
func (h *HostRouter) clonePatternItems() []RouterGlobItem {
var items []RouterGlobItem
if len(h.PatternItems) < 1 {
return items
}
items = make([]RouterGlobItem, len(h.PatternItems))
for i, v := range h.PatternItems {
items[i] = v
}
return items
}