forked from ulule/limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_http.go
38 lines (31 loc) · 979 Bytes
/
middleware_http.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
package limiter
// HTTPMiddleware is the middleware for basic http.Handler.
import (
"net/http"
"strconv"
)
// HTTPMiddleware is the basic HTTP middleware.
type HTTPMiddleware struct {
Limiter *Limiter
}
// NewHTTPMiddleware return a new instance of go-json-rest middleware.
func NewHTTPMiddleware(limiter *Limiter) *HTTPMiddleware {
return &HTTPMiddleware{Limiter: limiter}
}
// Handler the middleware handler.
func (m *HTTPMiddleware) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
context, err := m.Limiter.Get(GetIPKey(r))
if err != nil {
panic(err)
}
w.Header().Add("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10))
w.Header().Add("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10))
w.Header().Add("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10))
if context.Reached {
http.Error(w, "Limit exceeded", 429)
return
}
h.ServeHTTP(w, r)
})
}