Skip to content

Commit

Permalink
Enable case insensitive query param matching
Browse files Browse the repository at this point in the history
Unmarshalling body params with json.Unmarshal supports case-insensitive
matching against struct tags.  Matching query params case insensitive
provides a more sane and consistent experience for API consumers.

The original url.Values keys remain case sensitive.
  • Loading branch information
ready4god2513 authored and vishr committed Jul 3, 2018
1 parent ec7b497 commit 01cfe83
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,22 @@ func (b *DefaultBinder) bindData(ptr interface{}, data map[string][]string, tag
continue
}
}
inputValue, exists := data[inputFieldName]

var inputValue []string
var exists bool

// Go json.Unmarshal supports case insensitive binding. However the url
// params are bound case sensitive which is inconsistent. To fix this
// we must check all of the map values in a case-insensitive search.
inputFieldName = strings.ToLower(inputFieldName)
for k, v := range data {
if strings.ToLower(k) == inputFieldName {
inputValue = v
exists = true
break
}
}

if !exists {
continue
}
Expand Down
13 changes: 13 additions & 0 deletions bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,19 @@ func TestBindQueryParams(t *testing.T) {
}
}

func TestBindQueryParamsCaseInsensitive(t *testing.T) {
e := New()
req := httptest.NewRequest(GET, "/?ID=1&NAME=Jon+Snow", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
u := new(user)
err := c.Bind(u)
if assert.NoError(t, err) {
assert.Equal(t, 1, u.ID)
assert.Equal(t, "Jon Snow", u.Name)
}
}

func TestBindUnmarshalParam(t *testing.T) {
e := New()
req := httptest.NewRequest(GET, "/?ts=2016-12-06T19:09:05Z&sa=one,two,three&ta=2016-12-06T19:09:05Z&ta=2016-12-06T19:09:05Z&ST=baz", nil)
Expand Down

0 comments on commit 01cfe83

Please sign in to comment.