|
123456789101112131415161718192021222324252627282930 |
- package mw
-
- import (
- "errors"
- "net/http"
- "strconv"
-
- "github.com/afex/hystrix-go/hystrix"
- "github.com/gin-gonic/gin"
- )
-
- // 熔断器, 此组件需要在gin.Recovery中间之前进行调用, 否则可能会导致panic时候, 无法recovery, 正确顺序如下
- //r.Use(BreakerWrapper)
- //r.Use(gin.Recovery())
- func Breaker(c *gin.Context) {
- name := c.Request.Method + "-" + c.Request.RequestURI
- hystrix.Do(name, func() error {
- c.Next()
- statusCode := c.Writer.Status()
- if statusCode >= http.StatusInternalServerError {
- return errors.New("status code " + strconv.Itoa(statusCode))
- }
- return nil
- }, func(e error) error {
- if e == hystrix.ErrCircuitOpen {
- c.String(http.StatusAccepted, "请稍后重试") //todo 修改报错方法
- }
- return e
- })
- }
|