From 39d373d37b5d61f0d290a476977c591c59646f03 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Thu, 14 Apr 2022 11:39:21 +0800 Subject: [PATCH] fix: fix http post to support multipart/form-data header --- netutil/http_test.go | 24 ++++++++++++++++++++++++ netutil/net_internal.go | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/netutil/http_test.go b/netutil/http_test.go index 701f998..8a683cc 100644 --- a/netutil/http_test.go +++ b/netutil/http_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "io/ioutil" "log" + "net/url" "testing" "github.com/duke-git/lancet/internal" @@ -46,6 +47,29 @@ func TestHttpPost(t *testing.T) { t.Log("response: ", resp.StatusCode, string(body)) } +func TestHttpPostFormData(t *testing.T) { + apiUrl := "https://jsonplaceholder.typicode.com/todos" + header := map[string]string{ + // "Content-Type": "application/x-www-form-urlencoded", + "Content-Type": "multipart/form-data", + } + type Todo struct { + UserId int `json:"userId"` + Title string `json:"title"` + } + postData := url.Values{} + postData.Add("userId", "1") + postData.Add("title", "TestAddToDo") + + resp, err := HttpPost(apiUrl, header, postData, nil) + if err != nil { + log.Fatal(err) + t.FailNow() + } + body, _ := ioutil.ReadAll(resp.Body) + t.Log("response: ", resp.StatusCode, string(body)) +} + func TestHttpPut(t *testing.T) { url := "https://jsonplaceholder.typicode.com/todos/1" header := map[string]string{ diff --git a/netutil/net_internal.go b/netutil/net_internal.go index 7ecc8ce..11f451a 100644 --- a/netutil/net_internal.go +++ b/netutil/net_internal.go @@ -84,7 +84,7 @@ func setHeaderAndQueryAndBody(req *http.Request, reqUrl string, header, queryPar } if req.Header.Get("Content-Type") == "multipart/form-data" || req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" { formData := queryParam.(url.Values) - err = setBodyByte(req, formData.Encode()) + err = setBodyByte(req, []byte(formData.Encode())) } else { err = setBodyByte(req, body) }