go-wxhelper/utils/httpclient.go

54 lines
1.1 KiB
Go
Raw Permalink Normal View History

package utils
import (
"encoding/json"
"github.com/go-resty/resty/v2"
"log"
"time"
)
type HttpClient interface {
Post(api string, param map[string]any, response any, retryCount int) (err error)
}
type httpClient struct{}
// HttpClientUtils
// @description: Http客户端工具
// @return HttpClient
func HttpClientUtils() HttpClient {
return &httpClient{}
}
// Post
// @description: 发送Post请求
// @receiver c
// @param api
// @param param
// @param response
// @param retryCount
// @return err
func (c httpClient) Post(api string, param map[string]any, response any, retryCount int) (err error) {
if retryCount > 5 {
log.Printf("重试五次失败,停止发送")
return
}
pbs, _ := json.Marshal(param)
var r *resty.Response
r, err = resty.New().R().
SetHeader("Content-Type", "application/json;chartset=utf-8").
SetBody(string(pbs)).
SetResult(response).
Post(api)
if err != nil {
log.Printf("请求失败: %s", err.Error())
// 休眠五秒后重新发送
time.Sleep(5 * time.Second)
return c.Post(api, param, response, retryCount+1)
}
log.Printf("请求结果: %s", r.String())
return
}