Skip to content

Commit

Permalink
made file fieldnames explicit, rather than magic #nomagic
Browse files Browse the repository at this point in the history
  • Loading branch information
matryer committed Dec 9, 2017
1 parent 73d5562 commit 2c29d5d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 17 deletions.
20 changes: 8 additions & 12 deletions graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
Expand Down Expand Up @@ -88,12 +87,7 @@ func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error
}
}
for i := range req.files {
filename := fmt.Sprintf("file-%d", i+1)
if i == 0 {
// just use "file" for the first one
filename = "file"
}
part, err := writer.CreateFormFile(filename, req.files[i].Name)
part, err := writer.CreateFormFile(req.files[i].Field, req.files[i].Name)
if err != nil {
return errors.Wrap(err, "create form file")
}
Expand Down Expand Up @@ -181,15 +175,17 @@ func (req *Request) Var(key string, value interface{}) {
}

// File sets a file to upload.
func (req *Request) File(filename string, r io.Reader) {
func (req *Request) File(fieldname, filename string, r io.Reader) {
req.files = append(req.files, file{
Name: filename,
R: r,
Field: fieldname,
Name: filename,
R: r,
})
}

// file represents a file to upload.
type file struct {
Name string
R io.Reader
Field string
Name string
R io.Reader
}
6 changes: 1 addition & 5 deletions graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,10 @@ func TestFile(t *testing.T) {
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()

client := NewClient(srv.URL)

f := strings.NewReader(`This is a file`)

req := NewRequest("query {}")
req.File("filename.txt", f)

req.File("file", "filename.txt", f)
err := client.Run(ctx, req, nil)
is.NoErr(err)
}
Expand Down

0 comments on commit 2c29d5d

Please sign in to comment.