breakerhandler.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package handler
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/tal-tech/go-zero/core/breaker"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. "github.com/tal-tech/go-zero/core/stat"
  9. "github.com/tal-tech/go-zero/rest/httpx"
  10. "github.com/tal-tech/go-zero/rest/internal/security"
  11. )
  12. const breakerSeparator = "://"
  13. func BreakerHandler(method, path string, metrics *stat.Metrics) func(http.Handler) http.Handler {
  14. brk := breaker.NewBreaker(breaker.WithName(strings.Join([]string{method, path}, breakerSeparator)))
  15. return func(next http.Handler) http.Handler {
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. promise, err := brk.Allow()
  18. if err != nil {
  19. metrics.AddDrop()
  20. logx.Errorf("[http] dropped, %s - %s - %s",
  21. r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent())
  22. w.WriteHeader(http.StatusServiceUnavailable)
  23. return
  24. }
  25. cw := &security.WithCodeResponseWriter{Writer: w}
  26. defer func() {
  27. if cw.Code < http.StatusInternalServerError {
  28. promise.Accept()
  29. } else {
  30. promise.Reject(fmt.Sprintf("%d %s", cw.Code, http.StatusText(cw.Code)))
  31. }
  32. }()
  33. next.ServeHTTP(cw, r)
  34. })
  35. }
  36. }