Skip to content

Commit

Permalink
Merge pull request #403 from go-resty/enhancements
Browse files Browse the repository at this point in the history
  • Loading branch information
jeevatkm authored Jan 11, 2021
2 parents de83b7e + aa639ad commit b90c855
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 34 deletions.
54 changes: 38 additions & 16 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ var (
hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type")
hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length")
hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding")
hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization")
hdrLocationKey = http.CanonicalHeaderKey("Location")

plainTextType = "text/plain; charset=utf-8"
Expand Down Expand Up @@ -113,6 +112,10 @@ type Client struct {
JSONMarshal func(v interface{}) ([]byte, error)
JSONUnmarshal func(data []byte, v interface{}) error

// HeaderAuthorizationKey is used to set/access Request Authorization header
// value when `SetAuthToken` option is used.
HeaderAuthorizationKey string

jsonEscapeHTML bool
setContentLength bool
closeConnection bool
Expand Down Expand Up @@ -742,6 +745,22 @@ func (c *Client) SetDoNotParseResponse(parse bool) *Client {
return c
}

// SetPathParam method sets single URL path key-value pair in the
// Resty client instance.
// client.SetPathParam("userId", "[email protected]")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/[email protected]/details
// It replaces the value of the key while composing the request URL.
//
// Also it can be overridden at request level Path Params options,
// see `Request.SetPathParam` or `Request.SetPathParams`.
func (c *Client) SetPathParam(param, value string) *Client {
c.pathParams[param] = value
return c
}

// SetPathParams method sets multiple URL path key-value pairs at one go in the
// Resty client instance.
// client.SetPathParams(map[string]string{
Expand All @@ -752,11 +771,13 @@ func (c *Client) SetDoNotParseResponse(parse bool) *Client {
// Result:
// URL - /v1/users/{userId}/{subAccountId}/details
// Composed URL - /v1/users/[email protected]/100002/details
// It replace the value of the key while composing request URL. Also it can be
// overridden at request level Path Params options, see `Request.SetPathParams`.
// It replaces the value of the key while composing the request URL.
//
// Also it can be overridden at request level Path Params options,
// see `Request.SetPathParam` or `Request.SetPathParams`.
func (c *Client) SetPathParams(params map[string]string) *Client {
for p, v := range params {
c.pathParams[p] = v
c.SetPathParam(p, v)
}
return c
}
Expand Down Expand Up @@ -989,18 +1010,19 @@ func createClient(hc *http.Client) *Client {
}

c := &Client{ // not setting lang default values
QueryParam: url.Values{},
FormData: url.Values{},
Header: http.Header{},
Cookies: make([]*http.Cookie, 0),
RetryWaitTime: defaultWaitTime,
RetryMaxWaitTime: defaultMaxWaitTime,
JSONMarshal: json.Marshal,
JSONUnmarshal: json.Unmarshal,
jsonEscapeHTML: true,
httpClient: hc,
debugBodySizeLimit: math.MaxInt32,
pathParams: make(map[string]string),
QueryParam: url.Values{},
FormData: url.Values{},
Header: http.Header{},
Cookies: make([]*http.Cookie, 0),
RetryWaitTime: defaultWaitTime,
RetryMaxWaitTime: defaultMaxWaitTime,
JSONMarshal: json.Marshal,
JSONUnmarshal: json.Unmarshal,
HeaderAuthorizationKey: http.CanonicalHeaderKey("Authorization"),
jsonEscapeHTML: true,
httpClient: hc,
debugBodySizeLimit: math.MaxInt32,
pathParams: make(map[string]string),
}

// Logger
Expand Down
8 changes: 5 additions & 3 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ func createHTTPRequest(c *Client, r *Request) (err error) {
if r.bodyBuf == nil {
if reader, ok := r.Body.(io.Reader); ok {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader)
} else if c.setContentLength || r.setContentLength {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, http.NoBody)
} else {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil)
}
Expand Down Expand Up @@ -251,9 +253,9 @@ func addCredentials(c *Client, r *Request) error {

// Build the Token Auth header
if !IsStringEmpty(r.Token) { // takes precedence
r.RawRequest.Header.Set(hdrAuthorizationKey, authScheme+" "+r.Token)
r.RawRequest.Header.Set(c.HeaderAuthorizationKey, authScheme+" "+r.Token)
} else if !IsStringEmpty(c.Token) {
r.RawRequest.Header.Set(hdrAuthorizationKey, authScheme+" "+c.Token)
r.RawRequest.Header.Set(c.HeaderAuthorizationKey, authScheme+" "+c.Token)
}

return nil
Expand Down Expand Up @@ -540,4 +542,4 @@ func getBodyCopy(r *Request) (*bytes.Buffer, error) {
return bytes.NewBuffer(b), nil
}
return nil, nil
}
}
18 changes: 16 additions & 2 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,20 @@ func (r *Request) SetDoNotParseResponse(parse bool) *Request {
return r
}

// SetPathParam method sets single URL path key-value pair in the
// Resty current request instance.
// client.R().SetPathParam("userId", "[email protected]")
//
// Result:
// URL - /v1/users/{userId}/details
// Composed URL - /v1/users/[email protected]/details
// It replaces the value of the key while composing the request URL. Also you can
// override Path Params value, which was set at client instance level.
func (r *Request) SetPathParam(param, value string) *Request {
r.pathParams[param] = value
return r
}

// SetPathParams method sets multiple URL path key-value pairs at one go in the
// Resty current request instance.
// client.R().SetPathParams(map[string]string{
Expand All @@ -479,11 +493,11 @@ func (r *Request) SetDoNotParseResponse(parse bool) *Request {
// Result:
// URL - /v1/users/{userId}/{subAccountId}/details
// Composed URL - /v1/users/[email protected]/100002/details
// It replace the value of the key while composing request URL. Also you can
// It replaces the value of the key while composing request URL. Also you can
// override Path Params value, which was set at client instance level.
func (r *Request) SetPathParams(params map[string]string) *Request {
for p, v := range params {
r.pathParams[p] = v
r.SetPathParam(p, v)
}
return r
}
Expand Down
22 changes: 9 additions & 13 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1498,19 +1498,15 @@ func TestRequestExpectContentTypeTest(t *testing.T) {
assertEqual(t, "", firstNonEmpty("", ""))
}

func TestGetPathParams(t *testing.T) {
func TestGetPathParamAndPathParams(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()

c := dc()
c.SetHostURL(ts.URL).
SetPathParams(map[string]string{
"userId": "[email protected]",
})
c := dc().
SetHostURL(ts.URL).
SetPathParam("userId", "[email protected]")

resp, err := c.R().SetPathParams(map[string]string{
"subAccountId": "100002",
}).
resp, err := c.R().SetPathParam("subAccountId", "100002").
Get("/v1/users/{userId}/{subAccountId}/details")

assertError(t, err)
Expand Down Expand Up @@ -1808,12 +1804,12 @@ func TestDebugLoggerRequestBodyTooLarge(t *testing.T) {
assertEqual(t, true, strings.Contains(output.String(), "REQUEST TOO LARGE"))
}

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

c := dc()
resp, err := c.R().SetBody(map[string]string{"username":"testuser", "password": "testpass"}).
resp, err := c.R().SetBody(map[string]string{"username": "testuser", "password": "testpass"}).
Post(ts.URL + "/redirect")

assertNil(t, err)
Expand All @@ -1831,7 +1827,7 @@ func (b brokenReadCloser) Close() error {
return nil
}

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

Expand All @@ -1840,4 +1836,4 @@ func TestPostBodyError(t *testing.T) {
assertNotNil(t, err)
assertEqual(t, "read error", err.Error())
assertNil(t, resp)
}
}

0 comments on commit b90c855

Please sign in to comment.