拓展支持表单上传

This commit is contained in:
Yun
2023-11-08 09:47:27 +08:00
parent 7d8ea7458f
commit 0274580168
3 changed files with 84 additions and 23 deletions
+10 -8
View File
@@ -21,11 +21,12 @@ import (
type dataType string type dataType string
const ( const (
DataTypeForm dataType = "form" DataTypeForm dataType = "form"
DataTypeJson dataType = "json" DataTypeJson dataType = "json"
DataTypeXml dataType = "xml" DataTypeXml dataType = "xml"
DataTypeEncode dataType = "encode" DataTypeEncode dataType = "encode"
DataTypeText dataType = "text" DataTypeText dataType = "text"
DataTypeUrlEncoded dataType = "urlencode"
) )
type method string type method string
@@ -74,13 +75,13 @@ var (
type DialContext func(ctx context.Context, network, addr string) (net.Conn, error) type DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
type curlx struct { type curlx struct {
transport *http.Transport transport *http.Transport
timeOutSecond int timeOutSecond int
} }
func NewCurlx() *curlx { func NewCurlx() *curlx {
return &curlx{ return &curlx{
transport: &transport, transport: &transport,
timeOutSecond: 180, timeOutSecond: 180,
} }
} }
@@ -166,7 +167,7 @@ func (c *curlx) Send(ctx context.Context, p *CurlParams) (res string, httpcode i
func (c *curlx) sendExec(ctx context.Context, p *CurlParams) (resp *http.Response, err error) { func (c *curlx) sendExec(ctx context.Context, p *CurlParams) (resp *http.Response, err error) {
client := &http.Client{ client := &http.Client{
Timeout: time.Second * time.Duration(c.timeOutSecond), // 设置该条连接的超时 Timeout: time.Second * time.Duration(c.timeOutSecond), // 设置该条连接的超时
Transport: c.transport, // Transport: c.transport, //
} }
err = p.parseMethod() err = p.parseMethod()
@@ -213,6 +214,7 @@ func (c *curlx) sendExec(ctx context.Context, p *CurlParams) (resp *http.Respons
if err != nil { if err != nil {
return nil, err return nil, err
} }
// response.StatusCode
return response, nil return response, nil
} }
+41
View File
@@ -0,0 +1,41 @@
package curlx
import (
"context"
"fmt"
"io"
"os"
"testing"
)
func TestSendFile(t *testing.T) {
file, err := os.Open("./go.mod")
if err != nil {
panic(err)
}
defer file.Close()
b, _ := io.ReadAll(file)
s := []*FormParam{
{
Key: "file",
Name: file.Name(),
Action: "file",
Value: string(b),
},
}
p := &CurlParams{
Url: "http://tech-dev.sealmoo.com/api/material/upload",
Method: "POST",
Params: s,
Headers: map[string]interface{}{
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZW5hbnRfaWQiOjAsImNsaWVudF9pZCI6MCwidXNlcl9pZCI6MSwiZXhwIjoxNzAxMzk3NzkxfQ.9_uJ6y8I4JZTwgSenwHC_01nddLuI4zmgpyPhn5M6j8",
},
DataType: DataTypeForm,
}
resp, code, err := NewCurlx().Send(context.Background(), p)
fmt.Println(resp, code, err)
}
+33 -15
View File
@@ -6,12 +6,21 @@ import (
"encoding/xml" "encoding/xml"
"errors" "errors"
"io" "io"
"mime/multipart"
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
) )
type FormParam struct {
Key string `json:"key"` // 字段名
Action string `json:"action"` // 动作(file/text)
Name string `json:"name"` // 文件名
Bytes []byte `json:"bytes"` // 文件内容
Value string `json:"value"` // 值
}
/** /**
* 处理请求类型 * 处理请求类型
*/ */
@@ -80,6 +89,27 @@ func (p *CurlParams) parseParams() (str io.Reader, err error) {
if err == nil { if err == nil {
return bytes.NewReader(b), nil return bytes.NewReader(b), nil
} }
} else if p.DataType == DataTypeForm {
// 表单上传(可能有文件)
// 文件上传的
formParam, ok := p.Params.([]*FormParam)
if ok {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for _, v := range formParam {
if v.Action == "file" {
part, _ := writer.CreateFormFile(v.Key, v.Name)
io.Copy(part, strings.NewReader(v.Value))
} else {
_ = writer.WriteField(v.Key, v.Value)
}
}
writer.Close()
p.Headers["Content-Type"] = writer.FormDataContentType()
return body, nil
}
return nil, errors.New("表单上传的参数格式不正确")
} else if p.DataType == DataTypeXml { } else if p.DataType == DataTypeXml {
if _, ok := p.Headers["Content-Type"]; !ok { if _, ok := p.Headers["Content-Type"]; !ok {
p.Headers["Content-Type"] = "application/xml" p.Headers["Content-Type"] = "application/xml"
@@ -96,19 +126,6 @@ func (p *CurlParams) parseParams() (str io.Reader, err error) {
string_data = string(by) string_data = string(by)
} }
return strings.NewReader(string_data), nil return strings.NewReader(string_data), nil
// switch p.Params.(type) {
// case map[string]string:
// // 请求参数转换成xml结构
// b, err := goutils.Map2XML(p.Params.(map[string]string))
// if err == nil {
// return bytes.NewBuffer(b)
// }
// default:
// b, err := xml.Marshal(p.Params)
// if err == nil {
// return bytes.NewBuffer(b)
// }
// }
} else if p.DataType == DataTypeText { } else if p.DataType == DataTypeText {
if _, ok := p.Headers["Content-Type"]; !ok { if _, ok := p.Headers["Content-Type"]; !ok {
p.Headers["Content-Type"] = "text/plain" p.Headers["Content-Type"] = "text/plain"
@@ -123,8 +140,7 @@ func (p *CurlParams) parseParams() (str io.Reader, err error) {
} }
return strings.NewReader(string_data), nil return strings.NewReader(string_data), nil
} else { } else if p.DataType == DataTypeUrlEncoded {
// FORM,""
if _, ok := p.Headers["Content-Type"]; !ok { if _, ok := p.Headers["Content-Type"]; !ok {
p.Headers["Content-Type"] = "application/x-www-form-urlencoded" p.Headers["Content-Type"] = "application/x-www-form-urlencoded"
} }
@@ -165,6 +181,8 @@ func (p *CurlParams) parseParams() (str io.Reader, err error) {
} }
} }
return strings.NewReader(values.Encode()), nil return strings.NewReader(values.Encode()), nil
} else {
return nil, errors.New("不支持的数据类型")
} }
} }