github
30 of 30 new or added lines in 1 file covered. (100.0%)
444 of 506 relevant lines covered (87.75%)
6.99 hits per line
1 |
package rest
|
|
2 |
|
|
3 |
import (
|
|
4 |
"net/http"
|
|
5 |
) |
|
6 |
|
|
7 |
// Throttle middleware checks how many request in-fly and rejects with 503 if exceeded
|
|
|
func Throttle(limit int64) func(http.Handler) http.Handler { |
1✔ |
|
|
1✔ |
|
ch := make(chan struct{}, limit) |
1✔ |
|
return func(h http.Handler) http.Handler { |
2✔ |
|
|
1✔ |
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
103✔ |
|
|
102✔ |
|
if limit <= 0 { |
102✔ |
|
h.ServeHTTP(w, r) |
× |
|
return
|
× |
|
} |
× |
19 |
|
|
|
var acquired bool |
102✔ |
|
defer func() { |
204✔ |
|
if !acquired {
|
192✔ |
|
return
|
90✔ |
|
} |
90✔ |
|
select {
|
12✔ |
|
case <-ch:
|
12✔ |
|
return
|
12✔ |
|
default:
|
× |
|
return
|
× |
30 |
} |
|
31 |
}() |
|
32 |
|
|
|
select {
|
102✔ |
|
case ch <- struct{}{}: |
12✔ |
|
acquired = true
|
12✔ |
|
h.ServeHTTP(w, r) |
12✔ |
|
return
|
12✔ |
|
default:
|
90✔ |
|
w.WriteHeader(http.StatusServiceUnavailable) |
90✔ |
|
return
|
90✔ |
41 |
} |
|
42 |
} |
|
43 |
|
|
|
return http.HandlerFunc(fn)
|
1✔ |
45 |
} |
|
46 |
} |