-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrouter.go
More file actions
203 lines (165 loc) · 5.25 KB
/
router.go
File metadata and controls
203 lines (165 loc) · 5.25 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
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
package router
import (
"net/http"
"strings"
"github.com/netlify/netlify-commons/tracing"
"github.com/rs/cors"
"github.com/go-chi/chi"
"github.com/sebest/xff"
"github.com/sirupsen/logrus"
)
type chiWrapper struct {
chi chi.Router
version string
svcName string
tracingPrefix string
rootLogger logrus.FieldLogger
healthEndpoint string
healthHandler APIHandler
enableTracing bool
enableCORS bool
enableRecover bool
}
// Router wraps the chi router to make it slightly more accessible
type Router interface {
// Use appends one middleware onto the Router stack.
Use(fn Middleware)
// With adds an inline middleware for an endpoint handler.
With(fn Middleware) Router
// Route mounts a sub-Router along a `pattern`` string.
Route(pattern string, fn func(r Router))
// Method adds a routes for a `pattern` that matches the `method` HTTP method.
Method(method, pattern string, h APIHandler)
// HTTP-method routing along `pattern`
Delete(pattern string, h APIHandler)
Get(pattern string, h APIHandler)
Post(pattern string, h APIHandler)
Put(pattern string, h APIHandler)
// Mount attaches another http.Handler along ./pattern/*
Mount(pattern string, h http.Handler)
ServeHTTP(http.ResponseWriter, *http.Request)
// Returns the value of a URL parameter
URLParam(*http.Request, string) string
}
// New creates a router with sensible defaults (xff, request id, cors)
func New(log logrus.FieldLogger, options ...Option) Router {
r := &chiWrapper{
chi: chi.NewRouter(),
version: "unknown",
rootLogger: log,
}
xffmw, _ := xff.Default()
r.Use(xffmw.Handler)
for _, opt := range options {
opt(r)
}
if r.enableRecover {
r.Use(Recoverer(log))
}
r.Use(VersionHeader(r.svcName, r.version))
if r.enableCORS {
corsMiddleware := cors.New(cors.Options{
AllowedMethods: []string{"GET", "POST", "PATCH", "PUT", "DELETE"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link", "X-Total-Count"},
AllowCredentials: true,
})
r.Use(corsMiddleware.Handler)
}
if r.healthEndpoint != "" {
r.Use(HealthCheck(r.healthEndpoint, r.healthHandler))
}
return r
}
// Route allows creating a generic route
func (r *chiWrapper) Route(pattern string, fn func(Router)) {
r.chi.Route(pattern, func(c chi.Router) {
wrapper := new(chiWrapper)
*wrapper = *r
wrapper.chi = c
wrapper.tracingPrefix = sanitizePattern(pattern)
fn(wrapper)
})
}
// Method adds a routes for a `pattern` that matches the `method` HTTP method.
func (r *chiWrapper) Method(method, pattern string, h APIHandler) {
r.chi.Method(method, pattern, r.traceRequest(method, pattern, h))
}
// Get adds a GET route
func (r *chiWrapper) Get(pattern string, fn APIHandler) {
r.chi.Get(pattern, r.traceRequest(http.MethodGet, pattern, fn))
}
// Post adds a POST route
func (r *chiWrapper) Post(pattern string, fn APIHandler) {
r.chi.Post(pattern, r.traceRequest(http.MethodPost, pattern, fn))
}
// Put adds a PUT route
func (r *chiWrapper) Put(pattern string, fn APIHandler) {
r.chi.Put(pattern, r.traceRequest(http.MethodPut, pattern, fn))
}
// Delete adds a DELETE route
func (r *chiWrapper) Delete(pattern string, fn APIHandler) {
r.chi.Delete(pattern, r.traceRequest(http.MethodDelete, pattern, fn))
}
// WithBypass adds an inline chi middleware for an endpoint handler
func (r *chiWrapper) With(fn Middleware) Router {
r.chi = r.chi.With(fn)
return r
}
// UseBypass appends one chi middleware onto the Router stack
func (r *chiWrapper) Use(fn Middleware) {
r.chi.Use(fn)
}
// ServeHTTP will serve a request
func (r *chiWrapper) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.chi.ServeHTTP(w, req)
}
// Mount attaches another http.Handler along ./pattern/*
func (r *chiWrapper) Mount(pattern string, h http.Handler) {
if r.enableTracing {
h = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
tracing.TrackRequest(w, req, r.rootLogger, r.svcName, pattern, h)
})
}
r.chi.Mount(pattern, h)
}
// Returns the value of a URL parameter
func (r *chiWrapper) URLParam(req *http.Request, name string) string {
return chi.URLParam(req, name)
}
// =======================================
// HTTP handler with custom error payload
// =======================================
type APIHandler func(w http.ResponseWriter, r *http.Request) error
func HandlerFunc(fn APIHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := fn(w, r); err != nil {
HandleError(err, w, r)
}
}
}
func (r *chiWrapper) traceRequest(method, pattern string, fn APIHandler) http.HandlerFunc {
f := HandlerFunc(fn)
if r.enableTracing {
pattern = sanitizePattern(pattern)
if r.tracingPrefix != "" {
pattern = r.tracingPrefix + "." + pattern
}
resourceName := strings.ToUpper(method)
if pattern != "" {
resourceName += "::" + pattern
}
return func(w http.ResponseWriter, req *http.Request) {
tracing.TrackRequest(w, req, r.rootLogger, r.svcName, resourceName, f)
}
}
return f
}
func sanitizePattern(pattern string) string {
pattern = strings.TrimPrefix(pattern, "/")
pattern = strings.ReplaceAll(pattern, "{", "")
pattern = strings.ReplaceAll(pattern, "}", "")
pattern = strings.ReplaceAll(pattern, "/", ".")
pattern = strings.TrimSuffix(pattern, ".")
return pattern
}