123456789101112131415161718192021222324252627282930313233343536373839404142 |
- package handler
- import (
- "fmt"
- "net/http"
- "strings"
- "git.i2edu.net/i2/go-zero/core/breaker"
- "git.i2edu.net/i2/go-zero/core/logx"
- "git.i2edu.net/i2/go-zero/core/stat"
- "git.i2edu.net/i2/go-zero/rest/httpx"
- "git.i2edu.net/i2/go-zero/rest/internal/security"
- )
- const breakerSeparator = "://"
- // BreakerHandler returns a break circuit middleware.
- 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, httpx.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)
- })
- }
- }
|