Skip to content

Commit

Permalink
Add BodyFile
Browse files Browse the repository at this point in the history
  • Loading branch information
earthboundkid committed Jan 3, 2022
1 parent 2d91a48 commit 420645e
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
8 changes: 8 additions & 0 deletions body.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"net/url"
"os"
"strings"
)

Expand Down Expand Up @@ -60,3 +61,10 @@ func BodyForm(data url.Values) BodyGetter {
return io.NopCloser(strings.NewReader(data.Encode())), nil
}
}

// BodyFile is a BodyGetter that reads the provided file path.
func BodyFile(name string) BodyGetter {
return func() (r io.ReadCloser, err error) {
return os.Open(name)
}
}
7 changes: 6 additions & 1 deletion builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
// http.RoundTripper with Transport.
//
// Set the body of the request, if any, with Body or use built in BodyBytes,
// BodyForm, BodyJSON, BodyReader, or BodyWriter.
// BodyFile, BodyForm, BodyJSON, BodyReader, or BodyWriter.
//
// Add a response validator to the Builder with AddValidator or use the built
// in CheckStatus, CheckContentType, and Peek.
Expand Down Expand Up @@ -228,6 +228,11 @@ func (rb *Builder) BodyForm(data url.Values) *Builder {
ContentType("application/x-www-form-urlencoded")
}

// BodyFile sets the Builder's request body to read from the given file path.
func (rb *Builder) BodyFile(name string) *Builder {
return rb.Body(BodyFile(name))
}

// AddValidator adds a response validator to the Builder.
// Adding a validator disables DefaultValidator.
// To disable all validation, just add nil.
Expand Down
30 changes: 30 additions & 0 deletions builder_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,36 @@ func ExampleBuilder_BodyForm() {
// map[hello:world]
}

func ExampleBuilder_BodyFile() {
// Make a file to read from
d, err := os.MkdirTemp("", "body_file_*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(d) // clean up

exampleFilename := filepath.Join(d, "example.txt")
exampleContent := `hello, world`
if err = os.WriteFile(exampleFilename, []byte(exampleContent), 0644); err != nil {
log.Fatal(err)
}

// Post a raw file
var data postman
err = requests.
URL("https://postman-echo.com/post").
BodyFile(exampleFilename).
ContentType("text/plain").
ToJSON(&data).
Fetch(context.Background())
if err != nil {
fmt.Println("problem with postman:", err)
}
fmt.Println(data.Data)
// Output:
// hello, world
}

func ExampleBuilder_CheckPeek() {
// Check that a response has a doctype
const doctype = "<!doctype html>"
Expand Down

0 comments on commit 420645e

Please sign in to comment.