Skip to content

Commit

Permalink
feat(go-resty#432): Implement Easier Adding of Multiple Value HTTP He…
Browse files Browse the repository at this point in the history
…ader

Implement easier adding of multiple value HTTP Header with function `SetMultiValueHeaders`
  • Loading branch information
mhdiiilham committed Sep 1, 2021
1 parent 70336cb commit ae037fd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
26 changes: 26 additions & 0 deletions request.go
Expand Up @@ -117,6 +117,32 @@ func (r *Request) SetHeaders(headers map[string]string) *Request {
return r
}

// SetMultiValueHeaders sets multiple headers fields and its values is list of strings at one go in the current request.
//
// For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8`
//
// client.R().
// SetMultiValueHeaders(map[string][]string{
// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"},
// })
// Also you can override header value, which was set at client instance level.
func (r *Request) SetMultiValueHeaders(headers map[string][]string) *Request {
for key, values := range headers {
var headerValue string

if len(values) > 1 {
headerValue = strings.Join(values, ", ")
}

if len(values) == 1 {
headerValue = values[0]
}

r.SetHeader(key, headerValue)
}
return r
}

// SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request.
//
// For Example: To set `all_lowercase` and `UPPERCASE` as `available`.
Expand Down
12 changes: 12 additions & 0 deletions request_test.go
Expand Up @@ -1371,6 +1371,18 @@ func TestSetHeaderVerbatim(t *testing.T) {
assertEqual(t, "value_standard", r.Header.Get("Header-Lowercase"))
}

func TestSetHeaderMultipleValue(t *testing.T) {
ts := createPostServer(t)
defer ts.Close()

r := dclr().
SetMultiValueHeaders(map[string][]string{
"Content": []string{"text/*", "text/html", "*"},
"Authorization": []string{"Bearer xyz"},
})
assertEqual(t, "text/*, text/html, *", r.Header.Get("content"))
}

func TestOutputFileWithBaseDirAndRelativePath(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
Expand Down

0 comments on commit ae037fd

Please sign in to comment.