diff --git a/go.mod b/go.mod index 9f85ef1..8325db9 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/RambIing/urlValues -go 1.16 +go 1.18 diff --git a/urlValues.go b/urlValues.go index 254b1b2..1d7ab2e 100644 --- a/urlValues.go +++ b/urlValues.go @@ -6,6 +6,7 @@ package urlValues import ( + "slices" "sort" "strings" ) @@ -75,7 +76,9 @@ func (v Values) EncodeWithOrder() string { func (v Values) Add(key, value string) { v[key] = append(v[key], value) - v[OrderKey] = append(v[OrderKey], key) + if !slices.Contains(v[OrderKey], key) { + v[OrderKey] = append(v[OrderKey], key) + } } func (v Values) Del(key string) { diff --git a/urlValues_test.go b/urlValues_test.go index ee6d5dc..8b60200 100644 --- a/urlValues_test.go +++ b/urlValues_test.go @@ -8,39 +8,52 @@ func getValues() Values { values := Values{} values.Add("xyz", "abc") values.Add("abc", "xyz") + values.Add("foo", "bar") + values.Add("foo", "baa") + values.Add("foo", "baz") return values } func TestValues_Encode(t *testing.T) { values := getValues() - if values.Encode() != "abc=xyz&xyz=abc" { - t.FailNow() + encoded := values.Encode() + + if encoded != "abc=xyz&foo=bar&foo=baa&foo=baz&xyz=abc" { + t.Fatalf("failed to encode values. got: %s", encoded) } values.Del("xyz") - if values.EncodeWithOrder() != "abc=xyz" { - t.Fatalf("failed to delete item") + encoded = values.Encode() + + if encoded != "abc=xyz&foo=bar&foo=baa&foo=baz" { + t.Fatalf("failed to delete item. got: %s", encoded) } } func TestValues_EncodeWithOrder(t *testing.T) { values := getValues() - if values.EncodeWithOrder() != "xyz=abc&abc=xyz" { - t.FailNow() + encoded := values.EncodeWithOrder() + + if encoded != "xyz=abc&abc=xyz&foo=bar&foo=baa&foo=baz" { + t.Fatalf("failed to encode values with order. got: %s", encoded) } - values[OrderKey] = []string{"abc", "xyz"} + values[OrderKey] = []string{"abc", "xyz", "foo"} - if values.EncodeWithOrder() != "abc=xyz&xyz=abc" { - t.Fatalf("failed to manually rearrange order") + encoded = values.EncodeWithOrder() + + if encoded != "abc=xyz&xyz=abc&foo=bar&foo=baa&foo=baz" { + t.Fatalf("failed to encode values with new order. got: %s", encoded) } values.Del("abc") - if values.EncodeWithOrder() != "xyz=abc" && len(values[OrderKey]) != 1 { - t.Fatalf("failed to fully delete item") + encoded = values.EncodeWithOrder() + + if encoded != "xyz=abc&foo=bar&foo=baa&foo=baz" { + t.Fatalf("failed to delete item. got: %s", encoded) } }