From 64d430d424fce8b0ee80685b8d2ba753cd87bcbe Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Thu, 4 Apr 2024 20:28:54 +0800 Subject: [PATCH] fix: bug on form data with slices (#4040) --- rest/httpx/requests_test.go | 48 +++++++++++++++++++++++-------------- rest/httpx/util.go | 12 +++------- 2 files changed, 33 insertions(+), 27 deletions(-) diff --git a/rest/httpx/requests_test.go b/rest/httpx/requests_test.go index 157b1dbb..1a1c8a10 100644 --- a/rest/httpx/requests_test.go +++ b/rest/httpx/requests_test.go @@ -15,25 +15,37 @@ import ( ) func TestParseForm(t *testing.T) { - var v struct { - Name string `form:"name"` - Age int `form:"age"` - Percent float64 `form:"percent,optional"` - Statuses []string `form:"statuses,optional"` - NoValue string `form:"noValue,optional"` - } + t.Run("slice", func(t *testing.T) { + var v struct { + Name string `form:"name"` + Age int `form:"age"` + Percent float64 `form:"percent,optional"` + } - r, err := http.NewRequest( - http.MethodGet, - "/a?name=hello&age=18&percent=3.4&statuses=try&statuses=done", - http.NoBody) - assert.Nil(t, err) - assert.Nil(t, Parse(r, &v)) - assert.Equal(t, "hello", v.Name) - assert.Equal(t, 18, v.Age) - assert.Equal(t, 3.4, v.Percent) - assert.EqualValues(t, []string{"try", "done"}, v.Statuses) - assert.Equal(t, 0, len(v.NoValue)) + r, err := http.NewRequest( + http.MethodGet, + "/a?name=hello&age=18&percent=3.4", + http.NoBody) + assert.Nil(t, err) + assert.Nil(t, Parse(r, &v)) + assert.Equal(t, "hello", v.Name) + assert.Equal(t, 18, v.Age) + assert.Equal(t, 3.4, v.Percent) + }) + + t.Run("no value", func(t *testing.T) { + var v struct { + NoValue string `form:"noValue,optional"` + } + + r, err := http.NewRequest( + http.MethodGet, + "/a?name=hello&age=18&percent=3.4&statuses=try&statuses=done&singleValue=one", + http.NoBody) + assert.Nil(t, err) + assert.Nil(t, Parse(r, &v)) + assert.Equal(t, 0, len(v.NoValue)) + }) } func TestParseForm_Error(t *testing.T) { diff --git a/rest/httpx/util.go b/rest/httpx/util.go index 48d76592..9623761a 100644 --- a/rest/httpx/util.go +++ b/rest/httpx/util.go @@ -21,15 +21,9 @@ func GetFormValues(r *http.Request) (map[string]any, error) { params := make(map[string]any, len(r.Form)) for name := range r.Form { - switch len(r.Form[name]) { - case 1: - formValue := r.Form.Get(name) - if len(formValue) > 0 { - params[name] = formValue - } - default: - // len(r.Form[name]) > 1, never be 0 - params[name] = r.Form[name] + formValue := r.Form.Get(name) + if len(formValue) > 0 { + params[name] = formValue } }