You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.6 KiB
Go

package notify
import (
"bytes"
"context"
"joybuywork/internal/config"
"joybuywork/internal/consts"
"joybuywork/internal/repository/mtype"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/valyala/fasthttp"
)
const (
timeOut = 10 * time.Second
)
const (
ContentTypeJson = "application/json"
)
func normalReq(ctx context.Context, body []byte, notifyUrl, token, lang string, headers []*mtype.Header) (respBody string, code int, err error) {
req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(resp)
req.Header.SetMethod(fasthttp.MethodPost)
req.Header.Set(fasthttp.HeaderContentType, ContentTypeJson)
req.Header.Set("X-Message-Id", fmt.Sprint(ctx.Value(consts.TraceIdKey)))
req.Header.Set("X-Lang", lang)
req.Header.Set(fasthttp.HeaderAuthorization, fmt.Sprintf("Token %s", token))
for _, h := range headers {
switch h.Mark {
case mtype.NotifyUrlHeaderMarkLang:
req.Header.Set(h.Key, lang)
default:
req.Header.Set(h.Key, h.Val)
}
}
req.SetRequestURI(notifyUrl)
req.SetBody(body)
client := &fasthttp.Client{
ReadTimeout: timeOut,
WriteTimeout: timeOut,
}
err = client.Do(req, resp)
return string(resp.Body()), resp.StatusCode(), err
}
func proxyReq(ctx context.Context, body []byte, notifyUrl, token, lang string, headers []*mtype.Header) (respBody string, code int, err error) {
// 创建代理服务器的地址
proxyURL, err := url.Parse(config.Config.Server.LadderHost)
if err != nil {
err = errors.New(fmt.Sprintf("无法解析代理 URL: %v", err))
return
}
// 创建自定义的 HTTP 客户端
cli := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
reqBody := bytes.NewBuffer(body)
// 创建请求
req, err := http.NewRequest("POST", notifyUrl, reqBody)
if err != nil {
err = errors.New(fmt.Sprintf("创建请求失败: %v", err))
return
}
req.Header.Set(fasthttp.HeaderContentType, ContentTypeJson)
req.Header.Set("X-Message-Id", fmt.Sprint(ctx.Value(consts.TraceIdKey)))
req.Header.Set("X-Lang", lang)
req.Header.Set(fasthttp.HeaderAuthorization, fmt.Sprintf("Token %s", token))
for _, h := range headers {
switch h.Mark {
case mtype.NotifyUrlHeaderMarkLang:
req.Header.Set(h.Key, lang)
default:
req.Header.Set(h.Key, h.Val)
}
}
// 发送请求
resp, err := cli.Do(req)
if err != nil {
err = errors.New(fmt.Sprintf("请求失败: %v", err))
return
}
defer resp.Body.Close()
// 可以通过 resp.Body 获取响应内容
data, _ := io.ReadAll(resp.Body)
return string(data), resp.StatusCode, nil
}