-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
211 lines (169 loc) · 3.64 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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package serv
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/wmentor/latency"
"github.com/wmentor/tt"
"github.com/wmentor/uniq"
)
type Handler func(c *Context)
type ErrorHandler func(error)
type AuthCheck func(user string, passwd string) bool
type fileHandler struct {
Filename string
}
func (fh *fileHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
http.ServeFile(rw, req, fh.Filename)
}
type node struct {
name string
childs map[string]*node
wildCard bool
fn Handler
}
type router struct {
methods map[string]*node
redirects map[string]string
needUid bool
notFoundFunc Handler
badRequestFunc Handler
internalErrorFunc Handler
optionsFunc Handler
logger Logger
longQueryDuration time.Duration
longQueryHandler LongQueryHandler
errorHandler ErrorHandler
staticHandlers map[string]http.Handler
fileHandlers map[string]http.Handler
authCheck AuthCheck
tt *tt.TT
}
func (sr *router) optionsOrNotFound(c *Context) {
if sr.optionsFunc != nil && c.Method() == "OPTIONS" {
sr.optionsFunc(c)
} else {
sr.notFoundFunc(c)
}
}
func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if handler, has := r.fileHandlers[req.URL.Path]; has {
handler.ServeHTTP(rw, req)
return
}
for pref, handler := range r.staticHandlers {
if strings.HasPrefix(req.URL.Path, pref) {
handler.ServeHTTP(rw, req)
return
}
}
workTime := latency.New()
ctx := &Context{
rw: rw,
req: req,
params: make(map[string]string),
errorHandler: r.errorHandler,
tt: r.tt,
}
defer func() {
if r.logger != nil {
ld := &LogData{
Method: ctx.Method(),
Addr: ctx.RemoteAddr(),
Auth: "-",
RequestURL: ctx.req.RequestURI,
StatusCode: ctx.statusCode,
Referer: ctx.GetHeader("Referer"),
UserAgent: ctx.GetHeader("User-Agent"),
UID: ctx.Cookie("uid"),
}
if user, _, ok := ctx.BasicAuth(); ok {
ld.Auth = user
}
ld.Seconds = workTime.Seconds()
r.logger(ld)
}
if r.longQueryHandler != nil && r.longQueryDuration < workTime.Duration() {
r.longQueryHandler(workTime.Duration(), ctx)
}
}()
if r.needUid {
makeUid(rw, req)
}
if req.Method == http.MethodGet {
if dest, has := r.redirects[req.URL.Path]; has {
ctx.WriteRedirect(dest)
return
}
}
defer func() {
if re := recover(); re != nil {
r.internalErrorFunc(ctx)
if r.errorHandler != nil {
r.errorHandler(errors.New(fmt.Sprint(re)))
}
}
}()
root, has := r.methods[req.Method]
if !has {
r.optionsOrNotFound(ctx)
return
}
paths := path2list(req.URL.Path)
if len(paths) == 0 {
r.badRequestFunc(ctx)
return
}
tail := ""
params := make(map[string]string)
for _, item := range paths {
if root.wildCard {
tail += "/" + item
continue
}
if n, h := root.childs[""]; h {
root = n
if root.wildCard {
tail = "/" + item
} else {
params[root.name] = item
}
continue
}
if n, h := root.childs[item]; h {
root = n
continue
}
r.optionsOrNotFound(ctx)
return
}
if root.wildCard {
params["*"] = tail
}
if root.fn != nil {
ctx.params = params
root.fn(ctx)
} else {
r.optionsOrNotFound(ctx)
}
}
func makeUid(rw http.ResponseWriter, req *http.Request) {
c, err := req.Cookie("uid")
v := ""
if err != nil {
v = uniq.New()
} else {
v = c.Value
}
cookie := &http.Cookie{
Name: "uid",
Value: v,
Path: "/",
HttpOnly: true,
Expires: time.Unix(time.Now().Unix()+86400*366, 0),
}
req.AddCookie(cookie)
http.SetCookie(rw, cookie)
}