go-zero/rest/handler/sheddinghandler.go

65 lines
1.4 KiB
Go
Raw Normal View History

2020-07-29 18:00:04 +08:00
package handler
2020-07-26 17:09:05 +08:00
import (
"net/http"
"sync"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/load"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stat"
2020-08-12 12:25:52 +08:00
"github.com/tal-tech/go-zero/rest/httpx"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/rest/internal/security"
2020-07-26 17:09:05 +08:00
)
const serviceType = "api"
var (
sheddingStat *load.SheddingStat
lock sync.Mutex
)
2021-03-01 19:15:35 +08:00
// SheddingHandler returns a middleware that does load shedding.
2020-07-26 17:09:05 +08:00
func SheddingHandler(shedder load.Shedder, metrics *stat.Metrics) func(http.Handler) http.Handler {
if shedder == nil {
return func(next http.Handler) http.Handler {
return next
}
}
ensureSheddingStat()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sheddingStat.IncrementTotal()
promise, err := shedder.Allow()
if err != nil {
metrics.AddDrop()
sheddingStat.IncrementDrop()
logx.Errorf("[http] dropped, %s - %s - %s",
2020-08-12 12:25:52 +08:00
r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent())
2020-07-26 17:09:05 +08:00
w.WriteHeader(http.StatusServiceUnavailable)
return
}
2020-07-29 18:00:04 +08:00
cw := &security.WithCodeResponseWriter{Writer: w}
2020-07-26 17:09:05 +08:00
defer func() {
if cw.Code == http.StatusServiceUnavailable {
promise.Fail()
} else {
sheddingStat.IncrementPass()
promise.Pass()
}
}()
next.ServeHTTP(cw, r)
})
}
}
func ensureSheddingStat() {
lock.Lock()
if sheddingStat == nil {
sheddingStat = load.NewSheddingStat(serviceType)
}
lock.Unlock()
}