103 lines
2.5 KiB
Go
Raw Normal View History

2025-04-22 15:46:48 +08:00
package httpclient
import (
"admin/internal/errcode"
"admin/lib/xlog"
"encoding/json"
"io"
"net/http"
2025-04-26 13:50:26 +08:00
"net/url"
2025-04-22 15:46:48 +08:00
"strings"
"time"
)
func Request(addr string, method string, body interface{}, resData interface{}) error {
removeUrl := checkUrl(addr)
//xlog.Debugf("-->req url: %v", removeUrl)
var res *http.Response
var err error
if method != "get" {
var bodyReader io.Reader
if body != nil {
bodyBytes, err := json.Marshal(body)
if err != nil {
xlog.Warnf(err)
return errcode.New(errcode.ServerError, "数据解析失败:%v", err)
}
bodyReader = strings.NewReader(string(bodyBytes))
}
client := &http.Client{
Timeout: time.Second * 3,
}
req, err := http.NewRequest(method, removeUrl, bodyReader)
if err != nil {
xlog.Warnf(err)
return errcode.New(errcode.ServerError, "数据请求创建失败:%v", err)
}
res, err = client.Do(req)
if err != nil {
xlog.Warnf(err)
return errcode.New(errcode.ServerError, "数据请求失败:%v", err)
}
} else {
2025-04-26 13:50:26 +08:00
if params, ok := body.(*url.Values); ok {
removeUrl = removeUrl + "?" + params.Encode()
} else if params, ok := body.(map[string]string); ok {
values := &url.Values{}
for k, v := range params {
values.Add(k, v)
}
removeUrl = removeUrl + "?" + values.Encode()
} else {
paramsBin, err := json.Marshal(body)
if err != nil {
return errcode.New(errcode.ServerError, "get方法数据格式(%+v)不合法尝试json序列化再反序列化时序列化报错:%v", body, err)
}
params := make(map[string]string)
err = json.Unmarshal(paramsBin, &params)
if err != nil {
return errcode.New(errcode.ServerError, "get方法数据格式(%+v)不合法尝试json序列化再反序列化时反序列化报错:%v", body, err)
}
values := &url.Values{}
for k, v := range params {
values.Add(k, v)
}
removeUrl = removeUrl + "?" + values.Encode()
}
2025-04-22 15:46:48 +08:00
res, err = http.Get(removeUrl)
}
// 获取数据
defer res.Body.Close()
resBody, err := io.ReadAll(res.Body)
if err != nil {
xlog.Warnf(err)
return errcode.New(errcode.ServerError, "数据解析失败:%v", err)
}
2025-04-24 20:39:31 +08:00
if len(resBody) < 256 {
xlog.Debugf("request url:%v, rsp:%v", removeUrl, string(resBody))
}
2025-04-22 15:46:48 +08:00
if err = json.Unmarshal(resBody, resData); err != nil {
return errcode.New(errcode.ServerError, "数据(%v)格式错误:%v", string(resBody), err)
}
//xlog.Debugf("%+v", resData)
return nil
}
func checkUrl(u string) string {
if strings.Contains(u, `http://`) || strings.Contains(u, `https://`) {
return u
} else {
return `http://` + u
}
}