From d459e257bf38821104027d29125d27674501bb82 Mon Sep 17 00:00:00 2001 From: Tommy Chen Date: Fri, 6 Jul 2018 18:48:21 +0800 Subject: [PATCH] Use form headers in WriteMultipartForm CreateFormFile always set Content-Type header to application/octet-stream. Use CreatePart instead so all headers in the multipart form can be used. --- http.go | 2 +- http_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/http.go b/http.go index f8c38fc531..0ee78a2e7c 100644 --- a/http.go +++ b/http.go @@ -744,7 +744,7 @@ func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error { // marshal files for k, fvv := range f.File { for _, fv := range fvv { - vw, err := mw.CreateFormFile(k, fv.Filename) + vw, err := mw.CreatePart(fv.Header) if err != nil { return fmt.Errorf("cannot create form file %q (%q): %s", k, fv.Filename, err) } diff --git a/http_test.go b/http_test.go index 4052c6183c..7fbd905638 100644 --- a/http_test.go +++ b/http_test.go @@ -1811,3 +1811,32 @@ func createChunkedBody(body []byte) []byte { } return append(b, []byte("0\r\n\r\n")...) } + +func TestWriteMultipartForm(t *testing.T) { + var w bytes.Buffer + s := strings.Replace(`--foo +Content-Disposition: form-data; name="key" + +value +--foo +Content-Disposition: form-data; name="file"; filename="test.json" +Content-Type: application/json + +{"foo": "bar"} +--foo-- +`, "\n", "\r\n", -1) + mr := multipart.NewReader(strings.NewReader(s), "foo") + form, err := mr.ReadForm(1024) + + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + + if err := WriteMultipartForm(&w, form, "foo"); err != nil { + t.Fatalf("unexpected error: %s", err) + } + + if string(w.Bytes()) != s { + t.Fatalf("unexpected output %q", w.Bytes()) + } +}