forked from fasthttp/router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc.go
More file actions
50 lines (38 loc) · 1.69 KB
/
doc.go
File metadata and controls
50 lines (38 loc) · 1.69 KB
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
/*
A simple improvement upon standard net/http implementation of ServeMux, forked from fasthttp/router.
Thus, this multiplexer introduces optional and regex path params.
Grouping is also supported, but their ergonomics aren't traditional, instead you simply merge different handlers with Mux.Merge.
Inherits 0 allocation routing, except for redirects. This is a deliberate choice attempting to strip away any external deps from codebase.
Additionally, RedirectResolvedPath (RedirectFixedPath in `fasthttp/router`) works differently by utilizing url.ResolveReference method.
You _may_ want to disable redirects if you run into GC issues (but this router would probably be the least of your allocation problems anyway).
# Usage
mux := httx.NewMux()
mux.OnError = func(w http.ResponseWriter, r *http.Request, err error) {
// handle err
}
// Middleware must be initialized before any route
mux.Use(func(next httx.HandlerFunc) httx.HandlerFunc {
return func (w http.ResponseWriter, r *http.Request) error {
start := time.Now()
defer func() { // must defer stuff running after because panics
finish := time.Now()
slog.Info("request", "method", r.Method, "uri", r.RequestURI, "time-ms", finish.Sub(start).Milliseconds())
}()
return next(w, r)
}
})
mux.GET("/hello", func(w http.ResponseWriter, r *http.Request) error {
_, err := w.Write([]byte("world!"))
return err
})
mux.GET(`/{id:\d+}`, func(w http.ResponseWriter, r *http.Request) error {
id := r.PathValue("id") // Go's 1.22 PathValue-compatible
res, err := someDatabaseFunc(r.Context(), id)
if err != nil {
return err
}
return json.NewEncoder(w).Encode(res)
})
_ = http.ListenAndServe(":8080", mux)
*/
package httx