/
throttle.go
39 lines (33 loc) · 877 Bytes
/
throttle.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
package serve
import "net/http"
// Throttle returns a middleware that limits concurrent requests. The middleware
// will block the request and wait for a token. If the context is cancelled
// beforehand, "Too Many Requests" is returned.
func Throttle(concurrency int) func(http.Handler) http.Handler {
// create bucket
bucket := make(chan struct{}, concurrency)
// fill bucket
for i := 0; i < concurrency; i++ {
bucket <- struct{}{}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// get token
select {
case <-bucket:
case <-r.Context().Done():
w.WriteHeader(http.StatusTooManyRequests)
return
}
// ensure token is added back
defer func() {
select {
case bucket <- struct{}{}:
default:
}
}()
// call next
next.ServeHTTP(w, r)
})
}
}