breakerhandler.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. // BreakerHandler returns a break circuit middleware.
  14. func BreakerHandler(method, path string, metrics *stat.Metrics) func(http.Handler) http.Handler {
  15. brk := breaker.NewBreaker(breaker.WithName(strings.Join([]string{method, path}, breakerSeparator)))
  16. return func(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. promise, err := brk.Allow()
  19. if err != nil {
  20. metrics.AddDrop()
  21. logx.Errorf("[http] dropped, %s - %s - %s",
  22. r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent())
  23. w.WriteHeader(http.StatusServiceUnavailable)
  24. return
  25. }
  26. cw := &security.WithCodeResponseWriter{Writer: w}
  27. defer func() {
  28. if cw.Code < http.StatusInternalServerError {
  29. promise.Accept()
  30. } else {
  31. promise.Reject(fmt.Sprintf("%d %s", cw.Code, http.StatusText(cw.Code)))
  32. }
  33. }()
  34. next.ServeHTTP(cw, r)
  35. })
  36. }
  37. }