2 Star 9 Fork 1

os-lee/easy-paas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
flow_req_breaker.go 1.21 KB
一键复制 编辑 原始数据 按行查看 历史
lee 提交于 2024-07-11 15:01 . websocket路由支持url重写,负载均衡
package middleware_http
import (
"errors"
"fmt"
"gitee.com/os-lee/easy-paas/common"
"gitee.com/os-lee/easy-paas/common/e"
"gitee.com/os-lee/easy-paas/common/flow"
"github.com/gin-gonic/gin"
"github.com/sony/gobreaker/v2"
)
// FlowReqBreaker 是一个Gin中间件,它使用gobreaker来实现熔断器。
func FlowReqBreaker() gin.HandlerFunc {
return func(c *gin.Context) {
// 调用下一个处理函数,并将其包装在熔断器中
_, err := flow.BreakerHandler.Execute(func() ([]byte, error) {
c.Next()
// c.AbortWithError(e.ERROR, err) 添加的错误
if len(c.Errors) != 0 {
// 检测到后面中间件的错误,返回错误,让断路器统计
return nil, errors.New(fmt.Sprintf("BreakerHandler捕获错误: %v", c.Errors))
}
return nil, nil
})
// 判断错误是断路器被打开,直接返回结果,不代理服务了
if errors.Is(err, gobreaker.ErrOpenState) {
common.ResponseError(c, e.ErrGateway, err)
c.Abort()
return
}
}
}
// errToError 将panic的类型转换为gin.Error类型
func errToError(err interface{}) error {
switch v := err.(type) {
case string:
return errors.New(v)
case error:
return v
default:
return errors.New("unknown error")
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/os-lee/easy-paas.git
git@gitee.com:os-lee/easy-paas.git
os-lee
easy-paas
easy-paas
b4985bcf7af8

搜索帮助