Skip to content

Commit e2203b1

Browse files
authored
Sort map keys for QS args for GET requests (#1157)
* Sort map keys for QS args for GET requests * make coverage hit
1 parent ba6e949 commit e2203b1

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

common/http.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"net/url"
1313
"reflect"
1414
"regexp"
15+
"sort"
1516
"strings"
1617

1718
"github.com/google/go-querystring/query"
@@ -523,7 +524,12 @@ func makeRequestBody(method string, requestURL *string, data interface{}, marsha
523524
switch inputType.Kind() {
524525
case reflect.Map:
525526
s := []string{}
526-
for _, k := range inputVal.MapKeys() {
527+
keys := inputVal.MapKeys()
528+
// sort map keys by their string repr, so that tests can be deterministic
529+
sort.Slice(keys, func(i, j int) bool {
530+
return keys[i].String() < keys[j].String()
531+
})
532+
for _, k := range keys {
527533
v := inputVal.MapIndex(k)
528534
if v.IsZero() {
529535
continue

common/http_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,22 @@ func TestMakeRequestBody(t *testing.T) {
347347
assert.Equal(t, []byte("abc"), body)
348348
}
349349

350+
func TestMakeRequestBodyForMap(t *testing.T) {
351+
requestURL := "/a"
352+
_, err := makeRequestBody("GET", &requestURL, map[string]int{
353+
// i hope this will not trigger false positives too often
354+
"e": 1,
355+
"a": 2,
356+
"f": 3,
357+
"g": 4,
358+
"c": 5,
359+
"b": 6,
360+
"d": 7,
361+
}, true)
362+
require.NoError(t, err)
363+
assert.Equal(t, "/a?a=2&b=6&c=5&d=7&e=1&f=3&g=4", requestURL)
364+
}
365+
350366
func TestClient_HandleErrors(t *testing.T) {
351367
tests := []struct {
352368
name string

0 commit comments

Comments
 (0)