refactor(backend): 替换HTTP客户端库并优化请求逻辑

- 将 github.com/carlmjohnson/requests 替换为 github.com/go-resty/resty/v2
- 集成 otelresty 实现 OpenTelemetry 追踪
- 简化请求参数设置与响应解析逻辑
- 移除对 net/http 和 otelhttp 的直接依赖- 统一使用 resty 客户端处理超时和重试配置
This commit is contained in:
danial
2025-09-25 20:05:43 +08:00
parent 5141318c3f
commit f9c77cccb2
6 changed files with 25 additions and 49 deletions

2
go.mod
View File

@@ -10,7 +10,6 @@ require (
github.com/PuerkitoBio/goquery v1.10.3
github.com/bytedance/gopkg v0.1.3
github.com/bytedance/sonic v1.14.1
github.com/carlmjohnson/requests v0.24.3
github.com/dubonzi/otelresty v1.6.0
github.com/duke-git/lancet/v2 v2.3.7
github.com/forgoer/openssl v1.8.0
@@ -22,7 +21,6 @@ require (
github.com/natefinch/lumberjack v2.0.0+incompatible
github.com/prometheus/client_golang v1.23.2
github.com/redis/go-redis/v9 v9.13.0
github.com/rs/xid v1.6.0
github.com/shopspring/decimal v1.4.0
github.com/stretchr/testify v1.11.1
github.com/widuu/gojson v0.0.0-20170212122013-7da9d2cd949b

4
go.sum
View File

@@ -20,8 +20,6 @@ github.com/bytedance/sonic v1.14.1 h1:FBMC0zVz5XUmE4z9wF4Jey0An5FueFvOsTKKKtwIl7
github.com/bytedance/sonic v1.14.1/go.mod h1:gi6uhQLMbTdeP0muCnrjHLeCUPyb70ujhnNlhOylAFc=
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/carlmjohnson/requests v0.24.3 h1:LYcM/jVIVPkioigMjEAnBACXl2vb42TVqiC8EYNoaXQ=
github.com/carlmjohnson/requests v0.24.3/go.mod h1:duYA/jDnyZ6f3xbcF5PpZ9N8clgopubP2nK5i6MVMhU=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -108,8 +106,6 @@ github.com/redis/go-redis/v9 v9.13.0 h1:PpmlVykE0ODh8P43U0HqC+2NXHXwG+GUtQyz+MPK
github.com/redis/go-redis/v9 v9.13.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/shiena/ansicolor v0.0.0-20230509054315-a9deabde6e02 h1:v9ezJDHA1XGxViAUSIoO/Id7Fl63u6d0YmsAm+/p2hs=
github.com/shiena/ansicolor v0.0.0-20230509054315-a9deabde6e02/go.mod h1:RF16/A3L0xSa0oSERcnhd8Pu3IXSDZSK2gmGIMsttFE=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=

View File

@@ -4,12 +4,11 @@ import (
"context"
"gateway/internal/config"
"gateway/internal/otelTrace"
"net/http"
"net/url"
"strconv"
"github.com/carlmjohnson/requests"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"github.com/dubonzi/otelresty"
"github.com/go-resty/resty/v2"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
@@ -28,14 +27,18 @@ func GetIPIsRestricted(ctx context.Context, ip string, merchantDeployId int, ord
}{IsAllowed: true},
}
path, _ := url.JoinPath(config.GetConfig().GetForbiddenBackendHost(), "/api/restriction/location/checkIPAllowed")
err = requests.
URL(path).
Params(map[string][]string{
"ip": {ip},
"orderNo": {orderNo},
"cardPass": {cardPass},
"deviceId": {deviceId},
"merchantDeployID": {strconv.Itoa(merchantDeployId)},
}).Transport(otelhttp.NewTransport(http.DefaultTransport)).ToJSON(&response).Fetch(context.Background())
webClient := resty.New()
otelresty.TraceClient(webClient)
_, err = webClient.R().
SetContext(ctx).
SetQueryParams(map[string]string{
"ip": ip,
"orderNo": orderNo,
"cardPass": cardPass,
"deviceId": deviceId,
"merchantDeployID": strconv.Itoa(merchantDeployId),
}).
SetResult(&response).
Get(path)
return response.Data.IsAllowed, err
}

View File

@@ -25,7 +25,6 @@ import (
"go.uber.org/zap"
"github.com/beego/beego/v2/server/web"
"github.com/rs/xid"
"github.com/widuu/gojson"
)
@@ -59,7 +58,7 @@ func (c *DaiLiImpl) Scan(ctx context.Context, orderInfo order.OrderInfo, roadInf
params["service2"] = service2
params["apikey"] = apiKey
params["money"] = strconv.FormatFloat(orderInfo.OrderAmount, 'f', 2, 32)
params["nonce_str"] = xid.New().String()
params["nonce_str"] = utils.GenerateId()
params["mch_orderid"] = orderInfo.BankOrderId
params["notify_url"] = NOTITY_URL

View File

@@ -29,7 +29,6 @@ import (
"github.com/beego/beego/v2/client/httplib"
"github.com/beego/beego/v2/core/logs"
beego "github.com/beego/beego/v2/server/web"
"github.com/rs/xid"
"github.com/widuu/gojson"
)
@@ -349,7 +348,7 @@ func (c *KuaiFuImpl) BalanceQuery(roadInfo road.RoadInfo) float64 {
params := map[string]any{
"merchantKey": KF_PAY_KEY,
"timestamp": utils.GetNowTimesTamp(),
"merchantOrderId": xid.New().String(),
"merchantOrderId": utils.GenerateId(),
}
ctx := context.Background()
keys := utils.SortMap(params)

View File

@@ -14,11 +14,12 @@ import (
"strings"
"time"
"github.com/beego/beego/v2/client/httplib"
"github.com/dubonzi/otelresty"
"github.com/duke-git/lancet/v2/convertor"
"github.com/duke-git/lancet/v2/cryptor"
"github.com/duke-git/lancet/v2/maputil"
"github.com/duke-git/lancet/v2/structs"
"github.com/go-resty/resty/v2"
"github.com/widuu/gojson"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
@@ -66,31 +67,11 @@ func (s *SendCardTaskTypeJinke) CreateOrder(ctx context.Context, roadUid string,
NotifyUrl: fmt.Sprintf("%s/jinke/notify", config.GetConfig().GatewayAddr()),
Sign: "",
}
req := httplib.NewBeegoRequestWithCtx(ctx,
"https://jkapi-aibi-shagquw.jknba.com/api/v1/pay/unifiedOrder",
"POST",
)
// reqData := struct {
// MchId string `json:"mchId"`
// ProductId string `json:"productId"`
// OutTradeNo string `json:"outTradeNo"`
// Amount int `json:"amount"`
// ReqTime int64 `json:"reqTime"`
// NotifyUrl string `json:"notifyUrl"`
// sign string `json:"sign,omitempty"`
// }{
// MchId: "1010",
// ProductId: "114",
// OutTradeNo: orderNo,
// Amount: int(faceValue * 100),
// ReqTime: time.Now().UnixMilli(),
// NotifyUrl: fmt.Sprintf("%s/jinke/notify", config.GetConfig().GatewayAddr()),
// sign: "",
// }
params, _ := structs.ToMap(reqData)
reqData.Sign = s.sign(params, maputil.Keys(params), gojson.Json(roadInfo.Params).Get("key").Tostring())
req, _ = req.JSONBody(reqData)
resp, err := req.String()
webClient := resty.New().SetTimeout(time.Second * 5).SetRetryCount(3)
otelresty.TraceClient(webClient)
response, err := webClient.R().SetContext(ctx).SetBody(reqData).Post("https://jkapi-aibi-shagquw.jknba.com/api/v1/pay/unifiedOrder")
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("解析分解会结构失败", zap.Error(err))
return orderPoolItem, err
@@ -108,10 +89,10 @@ func (s *SendCardTaskTypeJinke) CreateOrder(ctx context.Context, roadUid string,
Sign string `json:"sign"`
} `json:"data"`
}{}
otelTrace.Logger.WithContext(ctx).Info("查询参数", zap.Any("response", resp), zap.Any("params", params), zap.Any("responseData", responseData))
err = json.Unmarshal([]byte(resp), responseData)
otelTrace.Logger.WithContext(ctx).Info("查询参数", zap.Any("response", response.String()), zap.Any("params", params))
err = json.Unmarshal(response.Body(), responseData)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("json解析失败", zap.Error(err), zap.Any("response", resp))
otelTrace.Logger.WithContext(ctx).Error("json解析失败", zap.Error(err))
return orderPoolItem, err
}
if responseData.Code != 0 {