-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy paththrottle.go
More file actions
46 lines (38 loc) · 743 Bytes
/
throttle.go
File metadata and controls
46 lines (38 loc) · 743 Bytes
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
package rest
import (
"net/http"
)
// Throttle middleware checks how many request in-fly and rejects with 503 if exceeded
func Throttle(limit int64) func(http.Handler) http.Handler {
ch := make(chan struct{}, limit)
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if limit <= 0 {
h.ServeHTTP(w, r)
return
}
var acquired bool
defer func() {
if !acquired {
return
}
select {
case <-ch:
return
default:
return
}
}()
select {
case ch <- struct{}{}:
acquired = true
h.ServeHTTP(w, r)
return
default:
w.WriteHeader(http.StatusServiceUnavailable)
return
}
}
return http.HandlerFunc(fn)
}
}