1 Star 1 Fork 1

xiaoyutab/xgotool

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
retry.go 2.69 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyutab 提交于 2026-06-11 14:11 +08:00 . feat(https): slog日志改造 + 性能优化
package https
import (
"encoding/json"
"errors"
"log/slog"
"strings"
"sync"
"time"
)
var _defaultRetryMu sync.Mutex // 保护并发写入 reportList
// 错误重试机制
func (c *CURL) retry() *CURL {
// 如果未启用重试机制,则直接返回
if c == nil || c.option.retry <= 0 {
return c
}
if c.option.retry-1 > 0 {
slog.Info("https request retry",
"uri", c.URI,
"retry", c.option.retry-1,
"interval", _default.retryList[c.option.retry-1].String(),
"error", c.Error,
)
}
if c.option.retry > 12 {
// 超过重传次数,直接进行结果返回
if c.option.retryUri != "" {
b, _ := json.Marshal(c.option.reportList)
go func() {
if r := New(c.option.retryUri).
WithOption(WithHttpsContinue(), WithNoLog()).
ParamJson(map[string]any{
"msg": "FAILED",
"report": string(b),
}).
PostJson(); r.Error != nil {
slog.Error("https retry report send failed",
"uri", c.URI,
"retry_uri", c.option.retryUri,
"error", r.Error,
)
}
}()
}
slog.Info("https request failed after max retries",
"uri", c.URI,
"method", c.option.method,
"total_attempts", c.option.retry,
)
return c
}
// 未到达重试次数的话
if c.Error == nil && c.option.successContent != "" && !strings.Contains(c.Body, c.option.successContent) {
c.Error = errors.New("返回结果中未找到 " + c.option.successContent + " 内容,重试中...")
}
if c.Error == nil {
msg := "SUCCESS"
if len(c.option.reportList) > 0 {
// 重试后成功
msg = "ATTEMPTED SUCCESS"
}
// 重试成功,则直接返回
_defaultRetryMu.Lock()
c.option.reportList = append(c.option.reportList, c.Body)
_defaultRetryMu.Unlock()
b, _ := json.Marshal(c.option.reportList)
go func() {
if r := New(c.option.retryUri).
WithOption(WithHttpsContinue(), WithNoLog()).
ParamJson(map[string]any{
"msg": msg,
"report": string(b),
}).
PostJson(); r.Error != nil {
slog.Error("https retry report send failed",
"uri", c.URI,
"retry_uri", c.option.retryUri,
"error", r.Error,
)
}
}()
if len(c.option.reportList) > 0 {
slog.Info("https request succeeded after retry",
"uri", c.URI,
"attempts", len(c.option.reportList)+1,
)
}
return c
}
// 重试失败,同步执行重试逻辑(在同一 goroutine 中阻塞等待),完成后回到调用方
_defaultRetryMu.Lock()
c.option.reportList = append(c.option.reportList, c.Error.Error())
_defaultRetryMu.Unlock()
c.Body = ""
c.Error = nil
time.Sleep(_default.retryList[c.option.retry-1])
c.option.retry++
switch c.option.method {
case "get":
c.Get()
case "post":
c.Post()
case "postjson":
c.PostJson()
}
return c
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xiaoyutab/xgotool.git
git@gitee.com:xiaoyutab/xgotool.git
xiaoyutab
xgotool
xgotool
v0.4.2

搜索帮助