Commit 61809cd1 authored by Brad Fitzpatrick's avatar Brad Fitzpatrick

net/url: sort keys in Encode; don't enumerate map randomly

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/6303098
parent f3474890
...@@ -7,7 +7,9 @@ ...@@ -7,7 +7,9 @@
package url package url
import ( import (
"bytes"
"errors" "errors"
"sort"
"strconv" "strconv"
"strings" "strings"
) )
...@@ -538,14 +540,24 @@ func (v Values) Encode() string { ...@@ -538,14 +540,24 @@ func (v Values) Encode() string {
if v == nil { if v == nil {
return "" return ""
} }
parts := make([]string, 0, len(v)) // will be large enough for most uses var buf bytes.Buffer
for k, vs := range v { keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := v[k]
prefix := QueryEscape(k) + "=" prefix := QueryEscape(k) + "="
for _, v := range vs { for _, v := range vs {
parts = append(parts, prefix+QueryEscape(v)) if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(QueryEscape(v))
} }
} }
return strings.Join(parts, "&") return buf.String()
} }
// resolvePath applies special path segments from refs and applies // resolvePath applies special path segments from refs and applies
......
...@@ -453,20 +453,24 @@ func TestEscape(t *testing.T) { ...@@ -453,20 +453,24 @@ func TestEscape(t *testing.T) {
//} //}
type EncodeQueryTest struct { type EncodeQueryTest struct {
m Values m Values
expected string expected string
expected1 string
} }
var encodeQueryTests = []EncodeQueryTest{ var encodeQueryTests = []EncodeQueryTest{
{nil, "", ""}, {nil, ""},
{Values{"q": {"puppies"}, "oe": {"utf8"}}, "q=puppies&oe=utf8", "oe=utf8&q=puppies"}, {Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"},
{Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7", "q=dogs&q=%26&q=7"}, {Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"},
{Values{
"a": {"a1", "a2", "a3"},
"b": {"b1", "b2", "b3"},
"c": {"c1", "c2", "c3"},
}, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"},
} }
func TestEncodeQuery(t *testing.T) { func TestEncodeQuery(t *testing.T) {
for _, tt := range encodeQueryTests { for _, tt := range encodeQueryTests {
if q := tt.m.Encode(); q != tt.expected && q != tt.expected1 { if q := tt.m.Encode(); q != tt.expected {
t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected) t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected)
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment