You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
895 B
Go
39 lines
895 B
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"github.com/zeromicro/go-zero/core/syncx"
|
|
"github.com/zeromicro/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)
|
|
}
|
|
})
|
|
}
|
|
}
|