@@ -3,6 +3,7 @@ package request
3
3
import (
4
4
"bytes"
5
5
"encoding/json"
6
+ "errors"
6
7
"fmt"
7
8
"io"
8
9
"io/ioutil"
@@ -50,9 +51,10 @@ type Params struct {
50
51
ExpectedResponseCode int
51
52
}
52
53
53
- // Do executes the request as specified in the request params
54
- // The response body will be parsed into the provided struct
55
- func Do (params Params , responseBody interface {}) (returnErr error ) {
54
+ // Do executes the request as specified in the request params.
55
+ // The response body will be parsed into the provided struct.
56
+ // Optionally, the headers will be copied if a header map was provided.
57
+ func Do (params Params , responseBody interface {}, responseHeaderArg ... http.Header ) (returnErr error ) {
56
58
req , err := createRequest (params )
57
59
if err != nil {
58
60
return fmt .Errorf ("failed to create request: %w" , err )
@@ -75,6 +77,11 @@ func Do(params Params, responseBody interface{}) (returnErr error) {
75
77
return err
76
78
}
77
79
80
+ err = populateResponseHeader (res , responseHeaderArg )
81
+ if err != nil {
82
+ return err
83
+ }
84
+
78
85
if responseBody == nil {
79
86
return nil
80
87
}
@@ -117,6 +124,8 @@ func DoWithStringResponse(params Params) (result string, returnErr error) {
117
124
118
125
// DoWithCustomClient is the same as Do but will make the request using the
119
126
// supplied http.Client instead of the cachedClient.
127
+ // TODO client should become the first parameter in the next major update
128
+ // so we can add the response headers at the end. They are currently not supported.
120
129
func DoWithCustomClient (params Params , responseBody interface {}, client * http.Client ) (returnErr error ) {
121
130
req , err := createRequest (params )
122
131
if err != nil {
@@ -244,3 +253,20 @@ func checkResponseCode(res *http.Response, expectedResponseCode int) error {
244
253
func isSuccessCode (statusCode int ) bool {
245
254
return 200 <= statusCode && statusCode <= 299
246
255
}
256
+
257
+ func populateResponseHeader (res * http.Response , responseHeaderArg []http.Header ) error {
258
+ if len (responseHeaderArg ) == 0 { // go-staticcheck says no need to check for nil separately.
259
+ return nil
260
+ }
261
+
262
+ if len (responseHeaderArg ) > 1 {
263
+ return errors .New ("too many arguments supplied" )
264
+ }
265
+
266
+ responseHeader := responseHeaderArg [0 ]
267
+ for key , value := range res .Header {
268
+ responseHeader [key ] = value
269
+ }
270
+
271
+ return nil
272
+ }
0 commit comments