Skip to content

Commit

Permalink
Implement Set on RequestValues
Browse files Browse the repository at this point in the history
  • Loading branch information
brandur committed May 24, 2016
1 parent 9896155 commit cf5ae54
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
20 changes: 16 additions & 4 deletions params.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ const (
endbefore = "ending_before"
)

// RequestValues is a Form implementation that allows duplicate keys and
// encodes its entries in the same order that they were added.
// RequestValues is a collection of values that can be submitted along with a
// request that specifically allows for duplicate keys and encodes its entries
// in the same order that they were added.
type RequestValues struct {
values []formValue
}
Expand All @@ -26,8 +27,7 @@ func (f *RequestValues) Add(key, val string) {
f.values = append(f.values, formValue{key, val})
}

// Encode encodes the form's values into “URL encoded” form
// ("bar=baz&foo=quux").
// Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux").
func (f *RequestValues) Encode() string {
var buf bytes.Buffer
for _, v := range f.values {
Expand All @@ -41,7 +41,19 @@ func (f *RequestValues) Encode() string {
return buf.String()
}

// Set sets the first instance of a parameter for the given key to the given
// value. If no parameters exist with the key, a new one is added.
//
// Note that Set is O(n) and may be quite slow for a very large parameter list.
func (f *RequestValues) Set(key, val string) {
for i, v := range f.values {
if v.Key == key {
f.values[i].Value = val
return
}
}

f.Add(key, val)
}

// A key/value tuple for use in the RequestValues type.
Expand Down
16 changes: 16 additions & 0 deletions params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ func TestRequestValues(t *testing.T) {
if expected != actual {
t.Fatalf("Expected encoded value of %v but got %v.", expected, actual)
}

values.Set("foo", "firstbar")

actual = values.Encode()
expected = "foo=firstbar&foo=bar&baz=bar"
if expected != actual {
t.Fatalf("Expected encoded value of %v but got %v.", expected, actual)
}

values.Set("new", "appended")

actual = values.Encode()
expected = "foo=firstbar&foo=bar&baz=bar&new=appended"
if expected != actual {
t.Fatalf("Expected encoded value of %v but got %v.", expected, actual)
}
}

func TestParamsWithExtras(t *testing.T) {
Expand Down

0 comments on commit cf5ae54

Please sign in to comment.