This repository has been archived by the owner on Aug 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux.go
93 lines (75 loc) · 2.11 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
package trailmux
import (
"net/http"
"strings"
)
type Routes map[string]http.Handler
func (routes Routes) Mux() Mux {
return NewMux(routes)
}
type Mux struct {
methods Routes
paths Routes
NoMatch http.Handler
}
func (mux Mux) NoMatchHandler(handler http.Handler) Mux {
mux.NoMatch = handler
return mux
}
func (mux Mux) ServeHTTP(res http.ResponseWriter, req *http.Request) {
for path, handler := range mux.paths {
if strings.HasPrefix(req.URL.Path, path) {
http.StripPrefix(path, handler).ServeHTTP(res, req)
return
}
}
for method, handler := range mux.methods {
if req.Method == method {
handler.ServeHTTP(res, req)
return
}
}
mux.NoMatch.ServeHTTP(res, req)
}
// NewMux sorts routes by method or path
// sets NoMatch to a default handler writing HTTP status 404
// when any path is added or when no method handlers are added.
// A method not allowed handler is maped to NoMatch when all handlers
// are HTTP Method strings
func NewMux(routes Routes) Mux {
var mux Mux
mux.methods, mux.paths = sortRoutes(routes)
if len(mux.paths) != 0 || len(mux.methods) == 0 {
mux.NoMatch = http.HandlerFunc(defaultNotFound)
} else {
mux.NoMatch = http.HandlerFunc(defaultMethodNotAllowed)
}
return mux
}
func sortRoutes(routes map[string]http.Handler) (map[string]http.Handler, map[string]http.Handler) {
methods, paths := make(map[string]http.Handler), make(map[string]http.Handler)
for key, handler := range routes {
if isMethod(key) {
methods[key] = handler
} else {
paths[key] = handler
}
}
return methods, paths
}
func defaultNotFound(res http.ResponseWriter, req *http.Request) {
http.Error(res, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
func defaultMethodNotAllowed(res http.ResponseWriter, req *http.Request) {
http.Error(res, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
func isMethod(key string) bool {
switch key {
case http.MethodGet, http.MethodHead, http.MethodPost,
http.MethodPut, http.MethodPatch, http.MethodDelete,
http.MethodConnect, http.MethodOptions, http.MethodTrace:
return true
default:
return false
}
}