-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtollbooth_chi.go
45 lines (37 loc) · 944 Bytes
/
tollbooth_chi.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
package tollbooth_chi
import (
"net/http"
"github.com/didip/tollbooth/v7"
"github.com/didip/tollbooth/v7/limiter"
)
func LimitHandler(lmt *limiter.Limiter) func(http.Handler) http.Handler {
return func(handler http.Handler) http.Handler {
wrapper := &limiterWrapper{
lmt: lmt,
}
wrapper.handler = handler
return wrapper
}
}
type limiterWrapper struct {
lmt *limiter.Limiter
handler http.Handler
}
func (l *limiterWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
select {
case <-ctx.Done():
http.Error(w, "Context was canceled", http.StatusServiceUnavailable)
return
default:
httpError := tollbooth.LimitByRequest(l.lmt, w, r)
if httpError != nil {
l.lmt.ExecOnLimitReached(w, r)
w.Header().Add("Content-Type", l.lmt.GetMessageContentType())
w.WriteHeader(httpError.StatusCode)
w.Write([]byte(httpError.Message))
return
}
l.handler.ServeHTTP(w, r)
}
}