Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"context"
"errors"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
Expand All @@ -13,6 +16,7 @@ import (

"github.com/carlmjohnson/requests"
"github.com/carlmjohnson/requests/internal/be"
"github.com/carlmjohnson/requests/reqtest"
)

func TestClone(t *testing.T) {
Expand Down Expand Up @@ -187,6 +191,42 @@ func TestContentLength(t *testing.T) {
}
}

func TestBodyMultipartBoundary(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name, boundary string
}{
{"random", ""},
{"token", "simple"},
{"colon", "a:b"},
{"space", "a b"},
} {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(1024); err != nil {
t.Logf("Content-Type %q: %v", r.Header.Get("Content-Type"), err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer r.MultipartForm.RemoveAll()
io.WriteString(w, r.FormValue("message"))
}))
defer srv.Close()

var got string
err := requests.
New(reqtest.Server(srv)).
Config(requests.BodyMultipart(tc.boundary, func(multi *multipart.Writer) error {
return multi.WriteField("message", "hello, world")
})).
ToString(&got).
Fetch(context.Background())
be.NilErr(t, err)
be.Equal(t, "hello, world", got)
})
}
}

func TestRequestClosesBodyOnError(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
Expand Down
3 changes: 2 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"compress/gzip"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http/httptest"
)
Expand Down Expand Up @@ -62,7 +63,7 @@ func BodyMultipart(boundary string, h func(multi *multipart.Writer) error) Confi
boundary = multi.Boundary()
}
rb.
ContentType("multipart/form-data; boundary=" + boundary).
ContentType(mime.FormatMediaType("multipart/form-data", map[string]string{"boundary": boundary})).
BodyWriter(func(w io.Writer) error {
multi := multipart.NewWriter(w)
if err := multi.SetBoundary(boundary); err != nil {
Expand Down
Loading