-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
76 lines (69 loc) · 2.25 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
package mid
import (
"net/http"
"sync/atomic"
"time"
)
// RequestThrottler creates a re-usable limiter for multiple http.Handlers
// If the server is too busy to handle the request within the timeout, then
// a "503 Service Unavailable" status will be sent and the connection closed.
func RequestThrottler(concurrentRequests int, timeout time.Duration) func(http.Handler) http.Handler {
sema := make(chan struct{}, concurrentRequests)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case sema <- struct{}{}:
next.ServeHTTP(w, r)
<-sema
case <-time.After(timeout):
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
case <-r.Context().Done():
return
}
})
}
}
// MaxBodySize limits the size of the request body to avoid a DOS with a large JSON structure
// Go does this internally for multipart bodies: https://golang.org/src/net/http/request.go#L1136
func MaxBodySize(next http.Handler, size int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, size)
next.ServeHTTP(w, r)
})
}
// RequestCounter is useful for counting requests for logging
func RequestCounter(duration time.Duration, callback func(uint64, chan struct{})) func(http.Handler) http.Handler {
closer := make(chan struct{})
var counter uint64
go func() {
for {
select {
case <-closer:
return
case <-time.After(duration):
callback(atomic.SwapUint64(&counter, 0), closer)
}
}
}()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddUint64(&counter, 1)
next.ServeHTTP(w, r)
})
}
}
// MustQueryParams circit breaker middleware only forwards requests which
// have the specified query params set
func MustQueryParams(h http.Handler, params ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
for _, param := range params {
if q.Get(param) == "" {
http.Error(w, "missing "+param, http.StatusBadRequest)
return // exit early
}
}
h.ServeHTTP(w, r) // all params present, proceed
})
}