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.
go-zero/rest/handler/maxconnshandler.go

39 lines
878 B
Go

4 years ago
package handler
4 years ago
import (
"net/http"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/syncx"
"github.com/tal-tech/go-zero/rest/internal"
4 years ago
)
// MaxConns returns a middleware that limit the concurrent connections.
4 years ago
func MaxConns(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 {
4 years ago
latch := syncx.NewLimit(n)
4 years ago
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
4 years ago
if latch.TryBorrow() {
4 years ago
defer func() {
4 years ago
if err := latch.Return(); err != nil {
4 years ago
logx.Error(err)
}
}()
next.ServeHTTP(w, r)
} else {
4 years ago
internal.Errorf(r, "concurrent connections over %d, rejected with code %d",
4 years ago
n, http.StatusServiceUnavailable)
w.WriteHeader(http.StatusServiceUnavailable)
}
})
}
}