rename ngin to rest
This commit is contained in:
41
rest/handler/breakerhandler.go
Normal file
41
rest/handler/breakerhandler.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"zero/core/breaker"
|
||||
"zero/core/logx"
|
||||
"zero/core/stat"
|
||||
"zero/rest/internal"
|
||||
"zero/rest/internal/security"
|
||||
)
|
||||
|
||||
const breakerSeparator = "://"
|
||||
|
||||
func BreakerHandler(method, path string, metrics *stat.Metrics) func(http.Handler) http.Handler {
|
||||
brk := breaker.NewBreaker(breaker.WithName(strings.Join([]string{method, path}, breakerSeparator)))
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
promise, err := brk.Allow()
|
||||
if err != nil {
|
||||
metrics.AddDrop()
|
||||
logx.Errorf("[http] dropped, %s - %s - %s",
|
||||
r.RequestURI, internal.GetRemoteAddr(r), r.UserAgent())
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
cw := &security.WithCodeResponseWriter{Writer: w}
|
||||
defer func() {
|
||||
if cw.Code < http.StatusInternalServerError {
|
||||
promise.Accept()
|
||||
} else {
|
||||
promise.Reject(fmt.Sprintf("%d %s", cw.Code, http.StatusText(cw.Code)))
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(cw, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user