diff --git a/unmarshal.go b/unmarshal.go index 3ff0a30..1a90132 100644 --- a/unmarshal.go +++ b/unmarshal.go @@ -1,10 +1,10 @@ package queryparam import ( - "reflect" "errors" - "net/url" "fmt" + "net/url" + "reflect" "strings" ) @@ -28,7 +28,7 @@ func delimiterFromField(field reflect.StructField) string { return defaultDelimiter } -func unmarshalField(v reflect.Value, t reflect.Type, i int, u *url.URL) error { +func unmarshalField(v reflect.Value, t reflect.Type, i int, qs url.Values) error { var ( field reflect.StructField paramVal string @@ -42,7 +42,7 @@ func unmarshalField(v reflect.Value, t reflect.Type, i int, u *url.URL) error { return nil } - paramVal = u.Query().Get(tagVal) + paramVal = qs.Get(tagVal) if len(paramVal) == 0 { return nil } @@ -75,8 +75,9 @@ func Unmarshal(u *url.URL, i interface{}) error { v := iVal.Elem() t := v.Type() + qs := u.Query() for i := 0; i < t.NumField(); i++ { - if err := unmarshalField(v, t, i, u); err != nil { + if err := unmarshalField(v, t, i, qs); err != nil { return err } } diff --git a/unmarshal_test.go b/unmarshal_test.go index 0e251e2..ea8627b 100644 --- a/unmarshal_test.go +++ b/unmarshal_test.go @@ -1,12 +1,13 @@ package queryparam_test import ( - "testing" - "github.com/tomwright/queryparam" - "net/url" - "net/http" "fmt" + "net/http" + "net/url" "reflect" + "testing" + + "github.com/tomwright/queryparam" ) // ExampleUnmarshal creates a dummy http request and unmarshals the data into a struct @@ -96,7 +97,7 @@ func TestUnmarshal(t *testing.T) { st.Errorf("unable to unmarshal url: %s", err) } - if ! reflect.DeepEqual(tc.Data, tc.OutputData) { + if !reflect.DeepEqual(tc.Data, tc.OutputData) { st.Errorf("expected `%v`, got `%v`", tc.OutputData, tc.Data) } }) @@ -120,7 +121,7 @@ func TestUnmarshal_BlankDelimiterUsesDefaultDelimiter(t *testing.T) { t.Errorf("unexpected error: %s", err) } - if exp, got := []string{"Tom", "Jim"}, req.Name; ! reflect.DeepEqual(exp, got) { + if exp, got := []string{"Tom", "Jim"}, req.Name; !reflect.DeepEqual(exp, got) { t.Errorf("unexpected result. expected `%v`, got `%v`", exp, got) } } @@ -209,3 +210,22 @@ func TestUnmarshal_InvalidFieldType(t *testing.T) { t.Errorf("unexpected error string. expected `%s`, got `%s`", exp, got) } } + +func BenchmarkUnmarshal(b *testing.B) { + + u, err := url.Parse("http://localhost:123?name=abcd&namelist=a,b,c&namelistdash=abc&age=12") + if err != nil { + b.FailNow() + } + + b.ResetTimer() + for i := 0; i < b.N; i++ { + data := testData{} + err = queryparam.Unmarshal(u, &data) + if err != nil { + b.FailNow() + } + } + b.StopTimer() + b.ReportAllocs() +}