Files
mayfly-go/server/pkg/httpx/httpx.go

277 lines
5.9 KiB
Go
Raw Normal View History

2025-04-15 21:42:31 +08:00
package httpx
2020-09-01 10:34:11 +08:00
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
2023-09-23 22:52:05 +08:00
"mayfly-go/pkg/logx"
2023-10-12 12:14:56 +08:00
"mayfly-go/pkg/utils/anyx"
"mayfly-go/pkg/utils/collx"
"mime/multipart"
2020-09-01 10:34:11 +08:00
"net/http"
"os"
2020-09-01 10:34:11 +08:00
"time"
2024-03-21 17:15:52 +08:00
2025-06-27 12:17:45 +08:00
"github.com/spf13/cast"
2020-09-01 10:34:11 +08:00
)
// 默认超时
const DefTimeout = 60
2025-04-15 21:42:31 +08:00
type Req struct {
2023-09-23 22:52:05 +08:00
client http.Client
2020-09-01 10:34:11 +08:00
url string
method string
timeout int
body io.Reader
header map[string]string
}
type MultipartFile struct {
FieldName string // 字段名
FileName string // 文件名
FilePath string // 文件路径,文件路径不为空,则优先读取文件路径的内容
Bytes []byte // 文件内容
}
2020-09-01 10:34:11 +08:00
// 创建一个请求
2025-04-15 21:42:31 +08:00
func NewReq(url string) *Req {
return &Req{url: url, client: http.Client{}}
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
func (r *Req) Url(url string) *Req {
2020-09-01 10:34:11 +08:00
r.url = url
return r
}
2025-04-15 21:42:31 +08:00
func (r *Req) Header(name, value string) *Req {
if r.header == nil {
r.header = make(map[string]string)
}
r.header[name] = value
return r
}
func (r *Req) Timeout(second int) *Req {
r.timeout = second
2020-09-01 10:34:11 +08:00
return r
}
2025-04-15 21:42:31 +08:00
func (r *Req) GetByQuery(queryMap collx.M) *Resp {
2020-09-01 10:34:11 +08:00
var params string
2023-09-23 22:52:05 +08:00
for k, v := range queryMap {
2020-09-01 10:34:11 +08:00
if params != "" {
params += "&"
}
2023-10-20 21:31:46 +08:00
params += k + "=" + anyx.ToString(v)
2020-09-01 10:34:11 +08:00
}
r.url += "?" + params
return r.Get()
}
2025-04-15 21:42:31 +08:00
func (r *Req) Get() *Resp {
2020-09-01 10:34:11 +08:00
r.method = "GET"
r.body = nil
2023-09-23 22:52:05 +08:00
return sendRequest(r)
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
func (r *Req) PostJson(body string) *Resp {
2020-09-01 10:34:11 +08:00
buf := bytes.NewBufferString(body)
r.method = "POST"
r.body = buf
if r.header == nil {
r.header = make(map[string]string)
}
r.header["Content-type"] = "application/json"
2023-09-23 22:52:05 +08:00
return sendRequest(r)
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
func (r *Req) PostObj(body any) *Resp {
2020-09-01 10:34:11 +08:00
marshal, err := json.Marshal(body)
if err != nil {
2025-04-15 21:42:31 +08:00
return &Resp{err: errors.New("解析json obj错误")}
2020-09-01 10:34:11 +08:00
}
return r.PostJson(string(marshal))
}
2025-04-15 21:42:31 +08:00
func (r *Req) PostForm(params string) *Resp {
2020-09-01 10:34:11 +08:00
buf := bytes.NewBufferString(params)
r.method = "POST"
r.body = buf
if r.header == nil {
r.header = make(map[string]string)
}
r.header["Content-type"] = "application/x-www-form-urlencoded"
2023-09-23 22:52:05 +08:00
return sendRequest(r)
2020-09-01 10:34:11 +08:00
}
func (r *Req) PutJson(body string) *Resp {
buf := bytes.NewBufferString(body)
r.method = "PUT"
r.body = buf
if r.header == nil {
r.header = make(map[string]string)
}
r.header["Content-type"] = "application/json"
return sendRequest(r)
}
func (r *Req) PutObj(body any) *Resp {
marshal, err := json.Marshal(body)
if err != nil {
return &Resp{err: errors.New("解析json obj错误")}
}
return r.PutJson(string(marshal))
}
2025-04-15 21:42:31 +08:00
func (r *Req) PostMulipart(files []MultipartFile, reqParams collx.M) *Resp {
buf := &bytes.Buffer{}
// 文件写入 buf
writer := multipart.NewWriter(buf)
for _, uploadFile := range files {
var reader io.Reader
// 如果文件路径不为空则读取该路径文件否则使用bytes
if uploadFile.FilePath != "" {
file, err := os.Open(uploadFile.FilePath)
if err != nil {
2025-04-15 21:42:31 +08:00
return &Resp{err: err}
}
defer file.Close()
reader = file
} else {
reader = bytes.NewBuffer(uploadFile.Bytes)
}
part, err := writer.CreateFormFile(uploadFile.FieldName, uploadFile.FileName)
if err != nil {
2025-04-15 21:42:31 +08:00
return &Resp{err: err}
}
2023-09-23 22:52:05 +08:00
io.Copy(part, reader)
}
// 如果有其他参数则写入body
for k, v := range reqParams {
2024-03-21 17:15:52 +08:00
if err := writer.WriteField(k, cast.ToString(v)); err != nil {
2025-04-15 21:42:31 +08:00
return &Resp{err: err}
}
}
if err := writer.Close(); err != nil {
2025-04-15 21:42:31 +08:00
return &Resp{err: err}
}
r.method = "POST"
r.body = buf
if r.header == nil {
r.header = make(map[string]string)
}
r.header["Content-type"] = writer.FormDataContentType()
2023-09-23 22:52:05 +08:00
return sendRequest(r)
}
2025-04-15 21:42:31 +08:00
func sendRequest(rw *Req) *Resp {
respWrapper := &Resp{}
2023-09-23 22:52:05 +08:00
timeout := rw.timeout
if timeout > 0 {
rw.client.Timeout = time.Duration(timeout) * time.Second
} else {
timeout = DefTimeout
}
2020-09-01 10:34:11 +08:00
2023-09-23 22:52:05 +08:00
req, err := http.NewRequest(rw.method, rw.url, rw.body)
if err != nil {
respWrapper.err = fmt.Errorf("创建请求错误-%s", err.Error())
return respWrapper
}
setRequestHeader(req, rw.header)
resp, err := rw.client.Do(req)
2025-04-15 21:42:31 +08:00
return &Resp{resp: resp, err: err}
2020-09-01 10:34:11 +08:00
}
2023-09-23 22:52:05 +08:00
func setRequestHeader(req *http.Request, header map[string]string) {
2025-04-15 21:42:31 +08:00
req.Header.Set("User-Agent", "golang/mayfly-go")
2023-09-23 22:52:05 +08:00
for k, v := range header {
req.Header.Set(k, v)
}
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
type Resp struct {
2023-09-23 22:52:05 +08:00
resp *http.Response
err error
}
2025-04-15 21:42:31 +08:00
// BodyTo 将响应体通过json解析转为指定结构体
func (r *Resp) BodyTo(ptr any) error {
2023-09-23 22:52:05 +08:00
bodyBytes, err := r.BodyBytes()
2020-09-01 10:34:11 +08:00
if err != nil {
2023-09-23 22:52:05 +08:00
return err
}
2025-04-15 21:42:31 +08:00
err = json.Unmarshal(bodyBytes, &ptr)
2023-09-23 22:52:05 +08:00
if err != nil {
return fmt.Errorf("解析响应体-json解析失败-%s", err.Error())
2020-09-01 10:34:11 +08:00
}
return nil
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
// BodyToString 将响应体转为strings
func (r *Resp) BodyToString() (string, error) {
2023-09-23 22:52:05 +08:00
bodyBytes, err := r.BodyBytes()
2020-09-01 10:34:11 +08:00
if err != nil {
2023-09-23 22:52:05 +08:00
return "", err
2020-09-01 10:34:11 +08:00
}
2023-09-23 22:52:05 +08:00
return string(bodyBytes), nil
}
2025-04-15 21:42:31 +08:00
// BodyToMap 将响应体通过json解析转为map
func (r *Resp) BodyToMap() (map[string]any, error) {
2023-09-23 22:52:05 +08:00
var res map[string]any
2025-04-15 21:42:31 +08:00
return res, r.BodyTo(&res)
2023-09-23 22:52:05 +08:00
}
2025-04-15 21:42:31 +08:00
// BodyBytes 获取响应体的字节数组
func (r *Resp) BodyBytes() ([]byte, error) {
bodyReader, err := r.BodyReader()
2020-09-01 10:34:11 +08:00
if err != nil {
2023-09-23 22:52:05 +08:00
return nil, err
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
defer bodyReader.Close()
body, err := io.ReadAll(bodyReader)
2023-09-23 22:52:05 +08:00
2020-09-01 10:34:11 +08:00
if err != nil {
2023-09-23 22:52:05 +08:00
return nil, fmt.Errorf("读取响应体数据失败-%s", err.Error())
2020-09-01 10:34:11 +08:00
}
2023-09-23 22:52:05 +08:00
return body, err
2020-09-01 10:34:11 +08:00
}
2025-04-15 21:42:31 +08:00
// BodyReader 获取响应体的reader
func (r *Resp) BodyReader() (io.ReadCloser, error) {
resp, err := r.GetHttpResp()
if err != nil {
return nil, err
}
return resp.Body, nil
}
// GetHttpResp 获取http响应结果结构体
func (r *Resp) GetHttpResp() (*http.Response, error) {
2023-09-23 22:52:05 +08:00
if r.err != nil {
return nil, fmt.Errorf("请求失败-%s", r.err.Error())
}
if r.resp == nil {
return nil, errors.New("请求失败-响应结构体为空,请检查请求url等信息")
2020-09-01 10:34:11 +08:00
}
2023-09-23 22:52:05 +08:00
statusCode := r.resp.StatusCode
if isFailureStatusCode(statusCode) {
logx.Warnf("请求响应状态码为为失败状态: %v", statusCode)
}
return r.resp, nil
2020-09-01 10:34:11 +08:00
}
2023-09-23 22:52:05 +08:00
func isFailureStatusCode(statusCode int) bool {
return statusCode < http.StatusOK || statusCode >= http.StatusBadRequest
2020-09-01 10:34:11 +08:00
}