-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
61 lines (53 loc) · 1.8 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
package httprouter
import (
"net/http"
"strings"
)
type defaultRouter struct {
resolver routeResolver
notFound http.Handler
methodNotAllowed http.Handler
monitor Monitor
}
func newRouter(resolver routeResolver, notFound, methodNotAllowed http.Handler, monitor Monitor) http.Handler {
return &defaultRouter{resolver: resolver, notFound: notFound, methodNotAllowed: methodNotAllowed, monitor: monitor}
}
func (this *defaultRouter) ServeHTTP(response http.ResponseWriter, request *http.Request) {
this.resolve(request).ServeHTTP(response, request)
}
func (this *defaultRouter) resolve(request *http.Request) http.Handler {
rawPath := request.RequestURI
if len(rawPath) == 0 {
rawPath = request.URL.Path
} else if index := strings.Index(rawPath, "?"); index >= 0 {
rawPath = rawPath[0:index]
}
if handler, resolved := this.resolver.Resolve(request.Method, rawPath); handler != nil {
this.monitor.Routed(request)
return handler
} else if resolved {
this.monitor.MethodNotAllowed(request)
return this.methodNotAllowed
} else {
this.monitor.MethodNotAllowed(request)
return this.notFound
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type recoveryRouter struct {
http.Handler
recovery RecoveryFunc
monitor Monitor
}
func newRecoveryRouter(handler http.Handler, recovery RecoveryFunc, monitor Monitor) *recoveryRouter {
return &recoveryRouter{Handler: handler, recovery: recovery, monitor: monitor}
}
func (this *recoveryRouter) ServeHTTP(response http.ResponseWriter, request *http.Request) {
defer func() {
if recovered := recover(); recovered != nil {
this.recovery(response, request, recovered)
this.monitor.Recovered(request, recovered)
}
}()
this.Handler.ServeHTTP(response, request)
}