Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/RambIing/urlValues

go 1.16
go 1.18
5 changes: 4 additions & 1 deletion urlValues.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package urlValues

import (
"slices"
"sort"
"strings"
)
Expand Down Expand Up @@ -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) {
Expand Down
35 changes: 24 additions & 11 deletions urlValues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}