-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
103 lines (93 loc) · 2.79 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
package middleware
import (
"context"
"fmt"
"net/http"
"strconv"
"sync/atomic"
"time"
"github.com/Sidddddarth/stats"
"github.com/gorilla/mux"
)
// this is to make sure that we don't have more than `maxClient` in-memory at any point of time. As, having more http client than `maxClient`
// may lead to gateway OOM kill.
func LimitConcurrentRequests(maxRequests int) func(http.Handler) http.Handler {
requests := make(chan struct{}, maxRequests)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if maxRequests != 0 {
select {
case requests <- struct{}{}:
defer func() {
<-requests
}()
default:
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
}
next.ServeHTTP(w, r)
})
}
}
func StatMiddleware(ctx context.Context, router *mux.Router, s stats.Stats, component string) func(http.Handler) http.Handler {
var concurrentRequests int32
activeClientCount := s.NewStat(fmt.Sprintf("%s.concurrent_requests_count", component), stats.GaugeType)
go func() {
for {
select {
case <-ctx.Done():
return
case <-time.After(10 * time.Second):
activeClientCount.Gauge(atomic.LoadInt32(&concurrentRequests))
}
}
}()
// getPath retrieves the path from the request.
// The matched route's template is used if a match is found,
// otherwise the request's URL path is used instead.
getPath := func(r *http.Request) string {
var match mux.RouteMatch
if router.Match(r, &match) {
if path, err := match.Route.GetPathTemplate(); err == nil {
return path
}
}
return r.URL.Path
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := newStatusCapturingWriter(w)
path := getPath(r)
start := time.Now()
atomic.AddInt32(&concurrentRequests, 1)
defer atomic.AddInt32(&concurrentRequests, -1)
next.ServeHTTP(sw, r)
s.NewSampledTaggedStat(
fmt.Sprintf("%s.response_time", component),
stats.TimerType,
map[string]string{
"reqType": path,
"method": r.Method,
"code": strconv.Itoa(sw.status),
}).Since(start)
})
}
}
// newStatusCapturingWriter returns a new, properly initialized statusCapturingWriter
func newStatusCapturingWriter(w http.ResponseWriter) *statusCapturingWriter {
return &statusCapturingWriter{
ResponseWriter: w,
status: http.StatusOK,
}
}
// statusCapturingWriter is a response writer decorator that captures the status code.
type statusCapturingWriter struct {
http.ResponseWriter
status int
}
// WriteHeader override the http.ResponseWriter's `WriteHeader` method
func (w *statusCapturingWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}