-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux.go
337 lines (293 loc) · 7.37 KB
/
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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package ich
import (
"errors"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/go-chi/chi/v5"
)
type namedRoute struct {
method string
pattern string
replacers map[string]*regexp.Regexp
}
type Mux struct {
chi.Router
prefix namedRoute
namedRoutes map[string]namedRoute
routeNames map[string]string
}
func New() *Mux {
return &Mux{
Router: chi.NewRouter(),
namedRoutes: make(map[string]namedRoute),
routeNames: make(map[string]string),
}
}
func (m *Mux) With(middlewares ...func(http.Handler) http.Handler) *Mux {
return &Mux{
Router: m.Router.With(middlewares...),
prefix: m.prefix,
namedRoutes: m.namedRoutes,
routeNames: m.routeNames,
}
}
func (m *Mux) Group(fn func(r *Mux)) *Mux {
mux := &Mux{
Router: m.Router.With(),
prefix: m.prefix,
namedRoutes: m.namedRoutes,
routeNames: m.routeNames,
}
if fn != nil {
fn(mux)
}
return mux
}
func (m *Mux) Route(pattern string, fn func(r *Mux)) *Mux {
mux := New()
if fn != nil {
fn(mux)
}
m.Mount(pattern, mux)
return mux
}
func (m *Mux) Mount(pattern string, h http.Handler) {
if mux, ok := h.(*Mux); ok {
m.Router.Mount(pattern, mux.Router)
for name, r := range mux.namedRoutes {
rr := namedRoute{
method: r.method,
pattern: concatPrefix(m.prefix.pattern, concatPrefix(pattern, r.pattern)),
replacers: make(map[string]*regexp.Regexp),
}
for param, replacer := range m.prefix.replacers {
rr.replacers[param] = replacer
}
for param, replacer := range compileReplacers(pattern) {
rr.replacers[param] = replacer
}
for param, replacer := range r.replacers {
rr.replacers[param] = replacer
}
m.namedRoutes[name] = rr
m.routeNames[rr.method+rr.pattern] = name
}
} else {
m.Router.Mount(pattern, h)
}
}
type Builder struct {
prefix namedRoute
namedRoutes map[string]namedRoute
routeNames map[string]string
method string
pattern string
}
func (b Builder) Name(name string) {
if name == "" {
return
}
if replacers := compileReplacers(b.pattern); replacers != nil {
r := namedRoute{
method: b.method,
pattern: concatPrefix(b.prefix.pattern, b.pattern),
replacers: replacers,
}
for param, replacer := range b.prefix.replacers {
r.replacers[param] = replacer
}
b.namedRoutes[name] = r
b.routeNames[b.method+b.pattern] = name
}
}
func (m *Mux) builder(method, pattern string) Builder {
return Builder{
namedRoutes: m.namedRoutes,
routeNames: m.routeNames,
prefix: m.prefix,
method: method,
pattern: pattern,
}
}
func (m *Mux) Handle(pattern string, h http.Handler) Builder {
m.Router.Handle(pattern, h)
return m.builder("", pattern)
}
func (m *Mux) HandleFunc(pattern string, h http.HandlerFunc) Builder {
m.Router.HandleFunc(pattern, h)
return m.builder("", pattern)
}
func (m *Mux) Method(method, pattern string, h http.Handler) Builder {
m.Router.Method(method, pattern, h)
return m.builder(method, pattern)
}
func (m *Mux) MethodFunc(method, pattern string, h http.HandlerFunc) Builder {
m.Router.MethodFunc(method, pattern, h)
return m.builder(method, pattern)
}
func (m *Mux) Connect(pattern string, h http.HandlerFunc) Builder {
m.Router.Connect(pattern, h)
return m.builder("CONNECT", pattern)
}
func (m *Mux) Delete(pattern string, h http.HandlerFunc) Builder {
m.Router.Delete(pattern, h)
return m.builder("DELETE", pattern)
}
func (m *Mux) Get(pattern string, h http.HandlerFunc) Builder {
m.Router.Get(pattern, h)
return m.builder("GET", pattern)
}
func (m *Mux) Head(pattern string, h http.HandlerFunc) Builder {
m.Router.Head(pattern, h)
return m.builder("HEAD", pattern)
}
func (m *Mux) Options(pattern string, h http.HandlerFunc) Builder {
m.Router.Options(pattern, h)
return m.builder("OPTIONS", pattern)
}
func (m *Mux) Patch(pattern string, h http.HandlerFunc) Builder {
m.Router.Patch(pattern, h)
return m.builder("PATCH", pattern)
}
func (m *Mux) Post(pattern string, h http.HandlerFunc) Builder {
m.Router.Post(pattern, h)
return m.builder("POST", pattern)
}
func (m *Mux) Put(pattern string, h http.HandlerFunc) Builder {
m.Router.Put(pattern, h)
return m.builder("PUT", pattern)
}
func (m *Mux) Trace(pattern string, h http.HandlerFunc) Builder {
m.Router.Trace(pattern, h)
return m.builder("TRACE", pattern)
}
func (m *Mux) RouteName(method, pattern string) string {
return m.routeNames[method+pattern]
}
// TODO check if param value matches regex
func (m *Mux) BuildPath(name string, params ...any) (*url.URL, error) {
route, ok := m.namedRoutes[name]
if !ok {
return nil, fmt.Errorf("ich: route '%s' not found", name)
}
pattern := route.pattern
remaining := len(route.replacers)
var q url.Values
for i := 0; i < len(params); i += 1 {
switch param := params[i].(type) {
case string:
if len(params) == i+1 {
return nil, errors.New("ich: string path params must be followed by another string")
}
i++
nextParam, ok := params[i].(string)
if !ok {
return nil, errors.New("ich: string path params must be followed by another string")
}
if replacer := route.replacers[param]; replacer != nil {
pattern = replacer.ReplaceAllString(pattern, nextParam)
remaining--
} else {
if q == nil {
q = make(url.Values)
}
q.Add(param, nextParam)
}
case []string:
if len(param)%2 != 0 {
return nil, errors.New("ich: string path params must be followed by another string")
}
for j := 0; j < len(param); j += 2 {
if replacer := route.replacers[param[j]]; replacer != nil {
pattern = replacer.ReplaceAllString(pattern, param[j+1])
remaining--
} else {
if q == nil {
q = make(url.Values)
}
q.Add(param[j], param[j+1])
}
}
case url.Values:
for k, vals := range param {
if q == nil {
q = make(url.Values)
}
for _, val := range vals {
q.Add(k, val)
}
}
default:
return nil, errors.New("ich: path params must be string, []string or url.Values")
}
}
if remaining > 0 {
return nil, errors.New("ich: missing route params")
}
u := &url.URL{
Path: pattern,
}
if q != nil {
u.RawQuery = q.Encode()
}
return u, nil
}
func (m *Mux) Path(name string, pairs ...any) *url.URL {
u, err := m.BuildPath(name, pairs...)
if err != nil {
panic(err)
}
return u
}
func compileReplacers(pattern string) map[string]*regexp.Regexp {
replacers := make(map[string]*regexp.Regexp)
// wildcards
if strings.HasSuffix(pattern, "*") {
replacers["*"] = regexp.MustCompile(`\*$`)
}
// params
for i := 0; i < len(pattern); i++ {
char := pattern[i]
if char == '{' {
i++
cc := 1
ps := i
pe := i
for ; i < len(pattern); i++ {
char = pattern[i]
if char == '{' {
cc++
} else if char == '}' {
cc--
if cc == 0 {
pe = i
break
}
}
}
// on unclosed { we just return and let chi do the error handling
if pe == ps {
return nil
}
param := pattern[ps:pe]
// param with regex
if idx := strings.Index(param, ":"); idx >= 0 {
replacers[param[:idx]] = regexp.MustCompile(`\{` + param[:idx] + `:.{` + fmt.Sprint(len(param[idx+1:])) + `}\}`)
} else {
replacers[param] = regexp.MustCompile(`\{` + param + `\}`)
}
}
}
return replacers
}
func concatPrefix(prefix, pattern string) string {
if len(pattern) > 1 && strings.HasSuffix(pattern, "/") {
prefix += pattern[:len(pattern)-1]
} else {
prefix += pattern
}
return prefix
}