1 Star 0 Fork 0

mosache / go-zero

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
maxconnshandler.go 806 Bytes
一键复制 编辑 原始数据 按行查看 历史
kevwan 提交于 2020-10-11 19:42 . update readme
package handler
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"
)
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 {
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)
}
})
}
}
1
https://gitee.com/mosache/go-zero.git
git@gitee.com:mosache/go-zero.git
mosache
go-zero
go-zero
dfb45c801a6c

搜索帮助