103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package httpclient
|
||
|
||
import (
|
||
"admin/internal/errcode"
|
||
"admin/lib/xlog"
|
||
"encoding/json"
|
||
"io"
|
||
"net/http"
|
||
"net/url"
|
||
"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 {
|
||
|
||
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, ¶ms)
|
||
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()
|
||
}
|
||
|
||
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)
|
||
}
|
||
|
||
if len(resBody) < 256 {
|
||
xlog.Debugf("request url:%v, rsp:%v", removeUrl, string(resBody))
|
||
}
|
||
|
||
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
|
||
}
|
||
}
|