-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttprouter.go
More file actions
110 lines (99 loc) · 2.32 KB
/
Copy pathhttprouter.go
File metadata and controls
110 lines (99 loc) · 2.32 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package httprouter
import (
"errors"
"net/http"
"path"
)
type Router struct {
handlers map[string]map[string]http.Handler
delegates map[string]map[string]http.Handler
}
var Default Router = Router{
handlers: make(map[string]map[string]http.Handler),
delegates: make(map[string]map[string]http.Handler),
}
func (receiver Router) Register(handler http.Handler, path string, method string) error {
var found bool
_, found = receiver.handlers[path]
if !found {
receiver.handlers[path] = make(map[string]http.Handler)
}
_, found = receiver.handlers[path][method]
if found {
return errors.New("this path and method are already registered")
}
receiver.handlers[path][method] = handler
return nil
}
func (receiver Router) DelegatePath(handler http.Handler, path string, method string) error {
var found bool
_, found = receiver.delegates[path]
if !found {
receiver.delegates[path] = make(map[string]http.Handler)
}
_, found = receiver.delegates[path][method]
if found {
return errors.New("this path and method are already registered")
}
receiver.delegates[path][method] = handler
return nil
}
func (receiver Router) handler(method string, selectedPath string) (http.Handler, int) {
var found bool
var handlers map[string]http.Handler
var handler http.Handler
selectedPath = path.Clean(selectedPath)
handlers, found = receiver.handlers[selectedPath]
if found {
handler, found = handlers[method]
if found {
return handler, 0
}
return nil, 405
}
handlers, found = receiver.delegates[selectedPath]
if !found {
var s string = selectedPath
for {
s = path.Clean(s)
handlers, found = receiver.delegates[s]
if found {
break
}
handlers, found = receiver.delegates[s+"/"]
if found {
break
}
s = path.Dir(s)
if s == "." || s == "/" {
break
}
}
}
if found {
handler, found = handlers[method]
if found {
return handler, 0
}
return nil, 405
}
return nil, 404
}
func (receiver Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
method := r.Method
path := r.URL.Path
handler, status := receiver.handler(method, path)
if nil == handler {
switch status {
case 405:
w.WriteHeader(405)
w.Write([]byte("405 Method Not Allowed"))
return
default:
w.WriteHeader(404)
w.Write([]byte("404 Not Found!"))
return
}
}
handler.ServeHTTP(w, r)
}