-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
77 lines (63 loc) · 1.54 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
package espresso
import (
"fmt"
"net/http"
"slices"
"strings"
)
type Router interface {
Use(middlewares ...HandleFunc)
WithPrefix(path string) Router
HandleFunc(handleFunc HandleFunc)
}
type router struct {
prefix string
middlewares []HandleFunc
mux *http.ServeMux
}
func (g *router) WithPrefix(path string) Router {
return &router{
prefix: strings.TrimRight(g.prefix, "/") + "/" + strings.Trim(path, "/"),
middlewares: g.middlewares[0:len(g.middlewares)],
mux: g.mux,
}
}
func (g *router) Use(middleware ...HandleFunc) {
g.middlewares = append(g.middlewares, middleware...)
}
func (g *router) HandleFunc(fn HandleFunc) {
g.handleFunc(fn)
}
func (g *router) handleFunc(fn HandleFunc) {
ctx := newBuildtimeContext()
defer func() {
v := recover()
if v != errBuilderEnd {
if v == nil {
v = fmt.Errorf("should call ctx.Endpoint().End()")
}
panic(v)
}
g.register(ctx, fn)
}()
_ = fn(ctx)
}
func (g *router) register(ctx *buildtimeContext, fn HandleFunc) {
path := strings.TrimRight(g.prefix, "/") + "/" + strings.TrimLeft(ctx.endpoint.Path, "/")
chains := slices.Clone(g.middlewares)
chains = append(chains, ctx.endpoint.ChainFuncs...)
chains = append(chains, fn)
endpoint := *ctx.endpoint
endpoint.Path = path
endpoint.ChainFuncs = chains
pattern := ctx.endpoint.Method + " " + path
g.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
ctx := &runtimeContext{
ctx: r.Context(),
endpoint: &endpoint,
request: r,
response: w,
}
ctx.Next()
})
}