广告平台(站长下代理使用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mw_breaker.go 768 B

2 月之前
123456789101112131415161718192021222324252627282930
  1. package mw
  2. import (
  3. "errors"
  4. "net/http"
  5. "strconv"
  6. "github.com/afex/hystrix-go/hystrix"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // 熔断器, 此组件需要在gin.Recovery中间之前进行调用, 否则可能会导致panic时候, 无法recovery, 正确顺序如下
  10. //r.Use(BreakerWrapper)
  11. //r.Use(gin.Recovery())
  12. func Breaker(c *gin.Context) {
  13. name := c.Request.Method + "-" + c.Request.RequestURI
  14. hystrix.Do(name, func() error {
  15. c.Next()
  16. statusCode := c.Writer.Status()
  17. if statusCode >= http.StatusInternalServerError {
  18. return errors.New("status code " + strconv.Itoa(statusCode))
  19. }
  20. return nil
  21. }, func(e error) error {
  22. if e == hystrix.ErrCircuitOpen {
  23. c.String(http.StatusAccepted, "请稍后重试") //todo 修改报错方法
  24. }
  25. return e
  26. })
  27. }