forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
107 lines (83 loc) · 2.13 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
package main
import (
"net/http"
"regexp"
"strings"
nanoid "github.com/matoous/go-nanoid"
)
const (
xRequestIDHeader = "X-Request-ID"
)
var (
requestIDRe = regexp.MustCompile(`^[A-Za-z0-9_\-]+$`)
)
type routeHandler func(string, http.ResponseWriter, *http.Request)
type panicHandler func(string, http.ResponseWriter, *http.Request, error)
type route struct {
Method string
Prefix string
Handler routeHandler
Exact bool
}
type router struct {
prefix string
Routes []*route
PanicHandler panicHandler
}
func (r *route) IsMatch(req *http.Request) bool {
if r.Method != req.Method {
return false
}
if r.Exact {
return req.URL.Path == r.Prefix
}
return strings.HasPrefix(req.URL.Path, r.Prefix)
}
func newRouter(prefix string) *router {
return &router{
prefix: prefix,
Routes: make([]*route, 0),
}
}
func (r *router) Add(method, prefix string, handler routeHandler, exact bool) {
r.Routes = append(
r.Routes,
&route{Method: method, Prefix: r.prefix + prefix, Handler: handler, Exact: exact},
)
}
func (r *router) GET(prefix string, handler routeHandler, exact bool) {
r.Add(http.MethodGet, prefix, handler, exact)
}
func (r *router) OPTIONS(prefix string, handler routeHandler, exact bool) {
r.Add(http.MethodOptions, prefix, handler, exact)
}
func (r *router) HEAD(prefix string, handler routeHandler, exact bool) {
r.Add(http.MethodHead, prefix, handler, exact)
}
func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
req = req.WithContext(setTimerSince(req.Context()))
reqID := req.Header.Get(xRequestIDHeader)
if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
reqID, _ = nanoid.Nanoid()
}
rw.Header().Set("Server", "imgproxy")
rw.Header().Set(xRequestIDHeader, reqID)
defer func() {
if rerr := recover(); rerr != nil {
if err, ok := rerr.(error); ok && r.PanicHandler != nil {
r.PanicHandler(reqID, rw, req, err)
} else {
panic(rerr)
}
}
}()
logRequest(reqID, req)
for _, rr := range r.Routes {
if rr.IsMatch(req) {
rr.Handler(reqID, rw, req)
return
}
}
logWarning("Route for %s is not defined", req.URL.Path)
rw.WriteHeader(404)
}