-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
82 lines (66 loc) · 1.74 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
package axum
import (
"net/http"
"path/filepath"
)
type Router struct {
routes []*RouteEntry
}
func NewRouter() *Router {
return &Router{
routes: make([]*RouteEntry, 0),
}
}
func (rt *Router) addRoute(method, path string, handler Service) *Router {
rt.routes = append(rt.routes, NewRouteEntry(method, path, handler))
return rt
}
func (rt *Router) Get(path string, handler Service) *Router {
return rt.addRoute(http.MethodGet, path, handler)
}
func (rt *Router) Post(path string, handler Service) *Router {
return rt.addRoute(http.MethodPost, path, handler)
}
func (rt *Router) Put(path string, handler Service) *Router {
return rt.addRoute(http.MethodPut, path, handler)
}
func (rt *Router) Delete(path string, handler Service) *Router {
return rt.addRoute(http.MethodDelete, path, handler)
}
func (rt *Router) Head(path string, handler Service) *Router {
return rt.addRoute(http.MethodHead, path, handler)
}
func (rt *Router) Patch(path string, handler Service) *Router {
return rt.addRoute(http.MethodPatch, path, handler)
}
func (rt *Router) SubRouter(path string, sub *Router) *Router {
for _, re := range sub.routes {
rt.routes = append(rt.routes, &RouteEntry{
Method: re.Method,
Path: filepath.Join(path, re.Path),
Handler: re.Handler,
})
}
return rt
}
func (rt *Router) Layer(layer Layer) *Router {
for _, re := range rt.routes {
re.Handler = layer.Layer(re.Handler)
}
return rt
}
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, re := range rt.routes {
if !re.Match(r) {
continue
}
packer := re.Handler.Handle(r)
rsp, err := packer.Pack()
if err != nil {
// TODO: packer failed error handling
}
_ = rsp // TODO: response handling
return
}
http.NotFound(w, r)
}