-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.go
390 lines (357 loc) · 11.5 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// Copyright 2024 Christian Thorseth Blach. All rights reserved.
// Use of this source code is governed by a GPLv3-style
// license that can be found in the LICENSE file.
package cmux
import(
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"reflect"
"strings"
"sync"
"time"
"unsafe"
)
var DefaultMux = &Mux{}
type Mux struct {
Before func(http.ResponseWriter, *http.Request, any, any) error
parent *Mux
methodHandlers map[string]*MethodHandler
metadata any
metadataRaw []byte
metadataType reflect.Type
servesDir bool /* Does the handlefunc serve a dir? (i.e. ends with '/') */
debugTimings bool
debug bool
dfltContentType string
/* Directly mapped muxes */
m map[string]*Mux
/* Linearly mapped muxes */
matchers []fmtMatcher
mutex sync.RWMutex
}
var methodHandlerType = reflect.TypeOf(MethodHandler{})
/* Fmt stuff */
type fmtMatcher struct {
Mux *Mux
Prefix string
Suffix string
FieldParser pathFieldParser
/* for parsing only */
Label string
Type reflect.Type
Size uintptr
}
/* Actual routing */
func (mux *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
r.Body = io.NopCloser(bytes.NewReader([]byte{}))
}
if mux.debug {
rawReq, err := httputil.DumpRequest(r, true)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to dump request: %s", err.Error())
} else {
fmt.Fprintf(os.Stderr, "Request = {\n%s\n}\n", string(rawReq))
}
}
if r.URL.Path[0] != '/' {
http.NotFound(w, r)
return
}
dirs := strings.Split(r.URL.Path, "/")[1:]
mux.mutex.RLock()
match, fallback, patches := mux.matchDir(dirs)
mux.mutex.RUnlock()
if match == nil {
match = fallback
if match == nil {
http.NotFound(w, r)
return
}
}
var mh *MethodHandler
if mh = match.methodHandlers[r.Method]; mh == nil {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if mux.dfltContentType != "" {
w.Header().Set("Content-Type", mux.dfltContentType)
}
var mdIf any = nil
mdRaw := make([]byte, len(match.metadataRaw))
if match.metadata != nil {
copy(mdRaw, match.metadataRaw)
mdPtr := unsafe.Pointer(unsafe.SliceData(mdRaw))
for _, patch := range patches {
dst := unsafe.Slice((*byte)(unsafe.Add(mdPtr, patch.Offset)), patch.Size)
src := unsafe.Slice((*byte)(patch.Source), patch.Size)
copy(dst, src)
}
mdIf = reflect.NewAt(match.metadataType.Elem(), mdPtr).Interface()
}
if mux.Before != nil {
if err := mux.Before(w, r, mdIf, mh.data); err != nil {
mux.handleErr(w, r, err)
return
}
}
var t0, t1 time.Time
if mux.debugTimings { t0 = time.Now() }
if err := mh.fn(w, r, mdIf); err != nil {
mux.handleErr(w, r, err)
}
if mux.debugTimings {
t1 = time.Now()
log.Println(t1.Sub(t0), r.URL.Path)
}
}
func (mux *Mux) mkRoute(path string, metadata any, methodHandlers map[string]*MethodHandler) {
mux.mutex.Lock()
if mux.m == nil { mux.m = map[string]*Mux{} }
defer mux.mutex.Unlock()
if path[0] != '/' { log.Fatalln("path must start with slash", path) }
dirs := strings.Split(path, "/")[1:]
servesDir := false
if dirs[len(dirs) - 1] == "" {
dirs = dirs[:len(dirs) - 1]
servesDir = true
}
for _, dir := range dirs {
preBracket, postBracket, found := strings.Cut(dir, "{")
if strings.Contains(preBracket, "}") {
log.Fatalln("unexpected end bracket not closing expresison")
}
if found {
/* found variable bracket: */
pathVar, rem, found := strings.Cut(postBracket, "}")
if !found {
log.Fatalln("missing end bracket")
}
if strings.Contains(pathVar, "{") {
log.Fatalln("nested brackets not allowed in expressions")
}
if metadata == nil {
log.Fatalln("metadata cannot be nil when using labels")
}
parserMap := parseStruct(metadata)
p, ok := parserMap[pathVar]
if !ok {
log.Fatalf("struct for %s does not contain field %s",
path, pathVar)
}
matcher := fmtMatcher{
Mux: &Mux {
parent: mux,
m: map[string]*Mux{},
},
Prefix: preBracket,
Suffix: rem,
FieldParser: p,
Label: pathVar,
Size: p.Size,
}
var mIdx int
var m fmtMatcher
for mIdx, m = range mux.matchers{
if m.Prefix == matcher.Prefix &&
m.Suffix == matcher.Suffix &&
m.FieldParser.Type == matcher.FieldParser.Type &&
m.Label == matcher.Label &&
m.Size == matcher.Size {
break
}
}
if mIdx < len(mux.matchers) {
mux = mux.matchers[mIdx].Mux
} else {
mux.matchers = append(mux.matchers, matcher)
mux = matcher.Mux
}
} else {
/* did not find variable bracket */
if dir == "" { log.Fatalln("empty dir name not permittede", path) }
nmux, ok := mux.m[dir]
if !ok {
mux.m[dir] = &Mux{
parent: mux,
m: map[string]*Mux{},
}
mux = mux.m[dir]
} else { mux = nmux }
}
}
mux.servesDir = servesDir
if mux.metadata = metadata; mux.metadata != nil {
mux.metadataType = reflect.TypeOf(mux.metadata)
rv := reflect.ValueOf(mux.metadata)
mux.metadataRaw = unsafe.Slice((*byte)(rv.UnsafePointer()), mux.metadataType.Elem().Size())
}
mux.methodHandlers = methodHandlers
}
// Returning an error that also implements HTTPResponder in a MethodHandler
// function will cause the server to call HTTPRespond and respond to
// the incoming request with the returned values. If the error is non-nil
// the response will be an error. If the error is nil, the response will be the JSON-encoded
// 'any' return value.
type HTTPResponder interface {
HTTPRespond() (any, error)
}
// Returning an error that also implements HTTPErrorResponder in a MethodHandler
// function will cause the server to call the HTTPError method and respond with the
// specified int as status code and JSON-encode the 'any' value as the body.
type HTTPErrorResponder interface {
HTTPError()(int, any)
}
func (mux *Mux) handleErr(w http.ResponseWriter, r *http.Request, err error) {
var her HTTPErrorResponder
var hr HTTPResponder
code := 200
var out any
if errors.As(err, &her) {
code, out = her.HTTPError()
} else if errors.As(err, &hr) {
out, err = hr.HTTPRespond()
if err != nil {
if errors.As(err, &her) {
code, out = her.HTTPError()
} else {
code = http.StatusInternalServerError
out = &struct{Error string `json:"error"`}{"internal server error"}
}
log.Printf("Encountered unexpected error at %s: %s", r.URL, err.Error())
}
} else {
code = http.StatusInternalServerError
out = &struct{Error string `json:"error"`}{"internal server error"}
log.Printf("Encountered unexpected error at %s: %s", r.URL, err.Error())
}
w.WriteHeader(code)
if b, ok := out.([]byte); ok {
w.Write(b)
} else {
json.NewEncoder(w).Encode(out)
}
if mux.debug {
res := http.Response {
StatusCode: code,
Proto: "HTTP/1.1",
Header: w.Header(),
}
rawRes, err := httputil.DumpResponse(&res, false)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to dump request: %s", err.Error())
} else {
fmt.Fprintf(os.Stderr, "Response = {\n%s", string(rawRes))
}
json.NewEncoder(os.Stderr).Encode(out)
fmt.Fprintf(os.Stderr, "\n}\n")
}
}
type codeResponder struct{
code int
error
}
func (r *codeResponder) HTTPError() (int, any) {
var str string
if str = r.error.Error(); str == "" {
str = "unknown error"
}
return r.code, struct{Error string `json:"error"`}{str}
}
func (r *codeResponder) Unwrap() error {
return r.error
}
// HTTPError creates an error that when returned in a MethodHandler
// makes the server reply with the specified error and HTTP code.
func WrapError(err error, code int) error {
if err.Error() == "" {
err = errors.New(http.StatusText(code))
}
return &codeResponder{
code: code,
error: err,
}
}
// HTTPError creates an error that when returned in a MethodHandler
// makes the server reply with the specified error message and HTTP code.
func HTTPError(err string, code int) error {
if err == "" {
err = http.StatusText(code)
}
return &codeResponder{
code: code,
error: errors.New(err),
}
}
// Bypassed data can be returned directly in method handler functions.
type BypassingData struct{
data any
}
// Bypass takes any data and transforms it into data
// that can be directly returned in method handler functions.
func Bypass(res any) BypassingData {
return BypassingData{res}
}
func (wd BypassingData) HTTPRespond()(any, error) {
return wd.data, nil
}
func (wd BypassingData) Error() string {
return "whitelisted data not working"
}
/*
* Attempt to match a dir
* If no exact match is found, it will attempt to fallback to a served dir,
* i.e. a folder served with / at the end, e.g. 'folder/'
*/
func (mux *Mux) matchDir(dirs []string) (*Mux, *Mux, []mdPatch) {
if len(dirs) == 0 {
return mux, nil, []mdPatch{}
}
dir := dirs[0]
dirs = dirs[1:]
var fallback *Mux
var fbPatches []mdPatch
/* Check for exact string matches */
nmux, ok := mux.m[dir]
if ok {
if match, fb, patches := nmux.matchDir(dirs); match != nil {
return match, nil, patches
} else {
fallback = fb
fbPatches = patches
}
}
/* Loop through the parsers, and see if they match */
for _, matcher := range mux.matchers {
if !strings.HasPrefix(dir, matcher.Prefix) ||
!strings.HasSuffix(dir[len(matcher.Prefix):], matcher.Suffix) {
continue
}
src, err := matcher.FieldParser.Fn(dir[len(matcher.Prefix):len(dir) - len(matcher.Suffix)])
if err != nil { continue }
patch := mdPatch{
Offset: matcher.FieldParser.Offset,
Source: src,
Size: matcher.FieldParser.Size,
}
if match, fb, patches := matcher.Mux.matchDir(dirs); match != nil {
/* Prepend to argList */
patches = append([]mdPatch{patch}, patches...)
return match, nil, patches
} else if fallback == nil {
fallback = fb
fbPatches = append([]mdPatch{patch}, patches...)
}
}
if fallback == nil && mux.servesDir {
return nil, mux, []mdPatch{}
}
return nil, fallback, fbPatches
}