/
handler.go
94 lines (70 loc) Β· 1.77 KB
/
handler.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
package chttp
import (
"net/http"
"regexp"
"sort"
"strings"
"github.com/gorilla/mux"
)
// NewHandlerParams holds the params needed for NewHandler.
type NewHandlerParams struct {
Routers []Router
GlobalMiddlewares []Middleware
}
// NewHandler creates a http.Handler with the given routes and middlewares.
// The handler can be used with a http.Server or as an argument to StartServer.
func NewHandler(p NewHandlerParams) http.Handler {
var (
muxRouter = mux.NewRouter()
muxHandler = http.NewServeMux()
)
for _, mw := range p.GlobalMiddlewares {
muxRouter.Use(mw.Handle)
}
routes := make([]Route, 0)
for _, router := range p.Routers {
routes = append(routes, router.Routes()...)
}
sortRoutes(routes)
for _, route := range routes {
handler := http.Handler(route.Handler)
for _, mw := range route.Middlewares {
handler = mw.Handle(handler)
}
muxRoute := muxRouter.Handle(route.Path, handler)
if len(route.Methods) > 0 {
muxRoute.Methods(route.Methods...)
}
}
muxHandler.Handle("/", muxRouter)
return muxHandler
}
func sortRoutes(routes []Route) {
const matcherPlaceholder = "{{matcher}}"
re := regexp.MustCompile(`(?U)(\{.*\})`)
sort.Slice(routes, func(i, j int) bool {
aPath := re.ReplaceAllString(routes[i].Path, matcherPlaceholder)
bPath := re.ReplaceAllString(routes[j].Path, matcherPlaceholder)
aParts := strings.Split(aPath, "/")
bParts := strings.Split(bPath, "/")
if aPath == "/" {
aParts = nil
}
if bPath == "/" {
bParts = nil
}
if len(aParts) != len(bParts) {
return len(aParts) > len(bParts)
}
for i, aPart := range aParts {
bPart := bParts[i]
if aPart == matcherPlaceholder {
return false
}
if bPart == matcherPlaceholder {
return true
}
}
return false
})
}