Skip to content

Commit

Permalink
#123 Preserve query string order partially (#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeevatkm authored Feb 6, 2018
1 parent c905657 commit d106797
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 6 deletions.
13 changes: 11 additions & 2 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func parseRequestURL(c *Client, r *Request) error {
}

// Adding Query Param
query := reqURL.Query()
query := make(url.Values)
for k, v := range c.QueryParam {
for _, iv := range v {
query.Add(k, iv)
Expand All @@ -61,7 +61,16 @@ func parseRequestURL(c *Client, r *Request) error {
}
}

reqURL.RawQuery = query.Encode()
// GitHub #123 Preserve query string order partially.
// Since not feasible in `SetQuery*` resty methods, because
// standrad package `url.Encode(...)` sorts the query params
// alphabetically
if IsStringEmpty(reqURL.RawQuery) {
reqURL.RawQuery = query.Encode()
} else {
reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode()
}

r.URL = reqURL.String()

return nil
Expand Down
8 changes: 5 additions & 3 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,12 @@ func (r *Request) SetMultiValueQueryParams(params url.Values) *Request {
// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")
//
func (r *Request) SetQueryString(query string) *Request {
values, err := url.ParseQuery(strings.TrimSpace(query))
params, err := url.ParseQuery(strings.TrimSpace(query))
if err == nil {
for k := range values {
r.QueryParam.Add(k, values.Get(k))
for p, v := range params {
for _, pv := range v {
r.QueryParam.Add(p, pv)
}
}
} else {
r.client.Log.Printf("ERROR [%v]", err)
Expand Down
19 changes: 18 additions & 1 deletion request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1254,9 +1254,26 @@ func TestReportMethodSupportsPayload(t *testing.T) {
c := dc()
resp, err := c.R().
SetBody("body").
Execute("REPORT", ts.URL + "/report")
Execute("REPORT", ts.URL+"/report")

assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())

}

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

resp, err := New().R().
SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
Get(ts.URL + "/?UniqueId=ead1d0ed-XXX-XXX-XXX-abb7612b3146&Translate=false&tempauth=eyJ0eXAiOiJKV1QiLC...HZEhwVnJ1d0NSUGVLaUpSaVNLRG5scz0&ApiVersion=2.0")

assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "200 OK", resp.Status())
assertNotNil(t, resp.Body())
assertEqual(t, "TestGet: text response", resp.String())

logResponse(t, resp)
}

0 comments on commit d106797

Please sign in to comment.