forked from zeromicro/go-zero
/
maxconnshandler.go
38 lines (32 loc) · 892 Bytes
/
maxconnshandler.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 handler
import (
"net/http"
"github.com/Peakchen/go-zero/core/logx"
"github.com/Peakchen/go-zero/core/syncx"
"github.com/Peakchen/go-zero/rest/internal"
)
// MaxConnsHandler returns a middleware that limit the concurrent connections.
func MaxConnsHandler(n int) func(http.Handler) http.Handler {
if n <= 0 {
return func(next http.Handler) http.Handler {
return next
}
}
return func(next http.Handler) http.Handler {
latch := syncx.NewLimit(n)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if latch.TryBorrow() {
defer func() {
if err := latch.Return(); err != nil {
logx.Error(err)
}
}()
next.ServeHTTP(w, r)
} else {
internal.Errorf(r, "concurrent connections over %d, rejected with code %d",
n, http.StatusServiceUnavailable)
w.WriteHeader(http.StatusServiceUnavailable)
}
})
}
}