Skip to content

Commit bd91370

Browse files
author
Jason Kao
committed
added header functionality to graphql.Request
1 parent 22fe7a5 commit bd91370

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

graphql.go

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import (
3838
"io"
3939
"mime/multipart"
4040
"net/http"
41+
"net/textproto"
4142

4243
"github.com/pkg/errors"
4344
)
@@ -122,6 +123,12 @@ func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error
122123
}
123124
r.Header.Set("Content-Type", writer.FormDataContentType())
124125
r.Header.Set("Accept", "application/json")
126+
for key, values := range req.Header {
127+
for _, value := range values {
128+
r.Header.Add(key, value)
129+
}
130+
}
131+
c.logf(">> headers: %v", r.Header)
125132
r = r.WithContext(ctx)
126133
res, err := c.httpClient.Do(r)
127134
if err != nil {
@@ -171,15 +178,17 @@ type graphResponse struct {
171178

172179
// Request is a GraphQL request.
173180
type Request struct {
174-
q string
175-
vars map[string]interface{}
176-
files []file
181+
q string
182+
vars map[string]interface{}
183+
files []file
184+
Header Header
177185
}
178186

179187
// NewRequest makes a new Request with the specified string.
180188
func NewRequest(q string) *Request {
181189
req := &Request{
182-
q: q,
190+
q: q,
191+
Header: make(map[string][]string),
183192
}
184193
return req
185194
}
@@ -201,6 +210,37 @@ func (req *Request) File(fieldname, filename string, r io.Reader) {
201210
})
202211
}
203212

213+
// A Header represents the key-value pairs in an HTTP header.
214+
type Header map[string][]string
215+
216+
// Add adds the key, value pair to the header.
217+
// It appends to any existing values associated with key.
218+
func (h Header) Add(key, value string) {
219+
textproto.MIMEHeader(h).Add(key, value)
220+
}
221+
222+
// Set sets the header entries associated with key to
223+
// the single element value. It replaces any existing
224+
// values associated with key.
225+
func (h Header) Set(key, value string) {
226+
textproto.MIMEHeader(h).Set(key, value)
227+
}
228+
229+
// Get gets the first value associated with the given key.
230+
// It is case insensitive; textproto.CanonicalMIMEHeaderKey is used
231+
// to canonicalize the provided key.
232+
// If there are no values associated with the key, Get returns "".
233+
// To access multiple values of a key, or to use non-canonical keys,
234+
// access the map directly.
235+
func (h Header) Get(key string) string {
236+
return textproto.MIMEHeader(h).Get(key)
237+
}
238+
239+
// Del deletes the values associated with key.
240+
func (h Header) Del(key string) {
241+
textproto.MIMEHeader(h).Del(key)
242+
}
243+
204244
// file represents a file to upload.
205245
type file struct {
206246
Field string

0 commit comments

Comments
 (0)