-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
272 lines (226 loc) · 7.18 KB
/
middleware.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package muxter
import (
"compress/gzip"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// Middleware is a function that takes a handler and modifies its behaviour by returning a new handler
type Middleware = func(Handler) Handler
func WithMiddleware(handler Handler, middlewares ...Middleware) Handler {
if handler == nil {
return nil
}
for i := len(middlewares) - 1; i >= 0; i-- {
handler = middlewares[i](handler)
}
return handler
}
// Recover allows you to register a handler function should a panic occur in the stack.
func Recover(recoverHandler func(recovered interface{}, w http.ResponseWriter, r *http.Request, c Context)) Middleware {
return func(h Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request, c Context) {
defer func() {
if recovered := recover(); r != nil {
recoverHandler(recovered, w, r, c)
return
}
}()
h.ServeHTTPx(w, r, c)
})
}
}
// AccessControlOptions provides options for the CORS middleware.
type AccessControlOptions struct {
// AllowOrigin is the origin that is set for the Access-Control-Allow-Origin. If it is "*" and
// AllowCredentials is true the incoming Origin will be used.
AllowOrigin string
// AllowOriginFunc takes the request origin and returns the Access-Control-Allow-Origin.
// Takes precedence over AllowOrigin.
AllowOriginFunc func(origin string) string
// MaxAge sets the Access-Control-Max-Age property.
MaxAge time.Duration
AllowCredentials bool
ExposeHeaders []string
AllowHeaders []string
AllowMethods []string
}
// CORS creates a middleware for enabling CORS with browsers.
func CORS(opts AccessControlOptions) Middleware {
if opts.AllowOrigin == "" {
opts.AllowOrigin = "*"
}
allowOrigin := opts.AllowOrigin
if opts.AllowMethods == nil {
opts.AllowMethods = []string{"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"}
}
allowMethods := strings.Join(opts.AllowMethods, ", ")
allowHeaders := strings.Join(opts.AllowHeaders, ", ")
return func(h Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request, c Context) {
if opts.AllowOriginFunc == nil && allowOrigin == "*" && opts.AllowCredentials {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Add("Vary", "Origin")
} else if opts.AllowOriginFunc != nil {
w.Header().Set("Access-Control-Allow-Origin", opts.AllowOriginFunc(r.Header.Get("Origin")))
w.Header().Add("Vary", "Origin") // Let browsers know that Access-Control-Allow-Origin varies by Origin
} else {
w.Header().Set("Access-Control-Allow-Origin", allowOrigin)
}
if opts.MaxAge > 0 {
w.Header().Set("Access-Control-Max-Age", strconv.Itoa(int(opts.MaxAge.Seconds())))
}
if opts.AllowCredentials {
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if strings.ToUpper(r.Method) == "OPTIONS" {
if allowHeaders != "" {
w.Header().Set("Access-Control-Allow-Headers", allowHeaders)
} else {
w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
w.Header().Add("Vary", "Access-Control-Request-Headers")
}
w.Header().Set("Access-Control-Allow-Methods", allowMethods)
w.WriteHeader(204)
return
}
h.ServeHTTPx(w, r, c)
})
}
}
// DefaultCORS is a non restrictive configuration of the CORS middleware. It defaults to accepting
// any origin for CORS requests, and accepting any set of preflight request headers. It does not
// however default to AllowCredentials:true, therefore if making credentialed CORS requests you must
// configure this via the standard CORS middleware function.
var DefaultCORS = CORS(AccessControlOptions{})
// Decompress modifies the request body who's content-encoding is gzip with a gzip.ReadCloser that reads from the original
// source body. All readers are closed safely after the main handler returns.
var Decompress Middleware = func(h Handler) Handler {
pool := sync.Pool{
New: func() interface{} {
return new(gzip.Reader)
},
}
return HandlerFunc(func(w http.ResponseWriter, r *http.Request, c Context) {
if r.Header.Get("Content-Encoding") != "gzip" {
h.ServeHTTPx(w, r, c)
return
}
gr := pool.Get().(*gzip.Reader)
defer pool.Put(gr)
if err := gr.Reset(r.Body); err != nil {
if errors.Is(err, io.EOF) {
h.ServeHTTPx(w, r, c)
return
}
http.Error(w, fmt.Sprintf("unexpected error: %v", err), 500)
return
}
// Only close gzip reader if gr.Reset is successful otherwise decompressor is not set and close will panic.
defer gr.Close()
originalReqBody := r.Body
defer originalReqBody.Close()
r.Body = gr
h.ServeHTTPx(w, r, c)
})
}
func Compress() Middleware {
hasGZIP := func(value string) bool {
for _, enc := range strings.Split(value, ",") {
enc = strings.TrimSpace(enc)
if enc == "gzip" {
return true
}
}
return false
}
return func(h Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request, c Context) {
if !hasGZIP(r.Header.Get("Accept-Encoding")) {
h.ServeHTTPx(w, r, c)
return
}
gw := gzipResponseWriter{
ResponseWriter: w,
gzip: gzip.NewWriter(w),
}
gw.Header().Set("Content-Encoding", "gzip")
h.ServeHTTPx(gw, r, c)
if err := gw.gzip.Close(); err != nil {
panic(err) // nothing else to do but panic and let users handle this in recovery middleware
}
})
}
}
type gzipResponseWriter struct {
http.ResponseWriter
gzip *gzip.Writer
}
func (w gzipResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
func (w gzipResponseWriter) Write(data []byte) (int, error) {
return w.gzip.Write(data)
}
// Skip decorates a middleware by giving it a predicate function for when this middleware should be skipped.
// if the predicateFunc returns true, the middleware is skipped.
func Skip(middleware Middleware, predicateFunc func(*http.Request) bool) Middleware {
return func(h Handler) Handler {
handlerWithMiddlewareApplied := middleware(h)
return HandlerFunc(func(w http.ResponseWriter, r *http.Request, c Context) {
if predicateFunc(r) {
h.ServeHTTPx(w, r, c)
return
}
handlerWithMiddlewareApplied.ServeHTTPx(w, r, c)
})
}
}
type RespOverview struct {
Request *http.Request
Response http.ResponseWriter
Context Context
Code int
TimeElapsed time.Duration
}
type responseProxy struct {
http.ResponseWriter
code int
}
func (w responseProxy) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func (w responseProxy) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
func (r *responseProxy) WriteHeader(code int) {
r.code = code
r.ResponseWriter.WriteHeader(code)
}
func (r responseProxy) Code() int {
if r.code == 0 {
return 200
}
return r.code
}
func Logger(dst io.Writer, fn func(overview RespOverview) string) Middleware {
return func(h Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request, c Context) {
proxy := responseProxy{w, 0}
start := time.Now()
h.ServeHTTPx(&proxy, r, c)
fmt.Fprintln(dst, fn(RespOverview{
Request: r,
Response: w,
Context: c,
Code: proxy.Code(),
TimeElapsed: time.Since(start),
}))
})
}
}