From 4061fba0a2a805859300c2af39d7acd779aed710 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jaworski?= Date: Tue, 9 Jul 2024 15:52:40 +0200 Subject: [PATCH] fix: make BindQueryParameter play along with x-go-type-skip-optional-pointer --- bindparam.go | 12 ++++++++---- bindparam_test.go | 10 ++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/bindparam.go b/bindparam.go index 63e42a3..f55aee8 100644 --- a/bindparam.go +++ b/bindparam.go @@ -318,7 +318,10 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str // inner code will bind the string's value to this interface. var output interface{} - if required { + // required params are never pointers, but it may happen that optional param + // is not pointer as well if user decides to annotate it with + // x-go-type-skip-optional-pointer + if required || v.Kind() != reflect.Pointer { // If the parameter is required, then the generated code will pass us // a pointer to it: &int, &object, and so forth. We can directly set // them. @@ -414,9 +417,10 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str if err != nil { return err } - // If the parameter is required, and we've successfully unmarshaled - // it, this assigns the new object to the pointer pointer. - if !required { + // If the parameter is required (or relies on x-go-type-skip-optional-pointer), + // and we've successfully unmarshaled it, this assigns the new object to the + // pointer pointer. + if !required && k == reflect.Pointer { dv.Set(reflect.ValueOf(output)) } return nil diff --git a/bindparam_test.go b/bindparam_test.go index 080f850..2c758f7 100644 --- a/bindparam_test.go +++ b/bindparam_test.go @@ -339,6 +339,7 @@ func TestBindQueryParameter(t *testing.T) { queryParams := url.Values{ "time": {"2020-12-09T16:09:53+00:00"}, "number": {"100"}, + "text": {"loremipsum"}, } // An optional time will be a pointer to a time in a parameter object var optionalTime *time.Time @@ -351,6 +352,15 @@ func TestBindQueryParameter(t *testing.T) { require.NoError(t, err) assert.Nil(t, optionalNumber) + var optionalNonPointerText = "" + err = BindQueryParameter("form", true, false, "notfound", queryParams, &optionalNonPointerText) + require.NoError(t, err) + assert.Zero(t, "") + + err = BindQueryParameter("form", true, false, "text", queryParams, &optionalNonPointerText) + require.NoError(t, err) + assert.Equal(t, "loremipsum", optionalNonPointerText) + // If we require values, we require errors when they're not present. err = BindQueryParameter("form", true, true, "notfound", queryParams, &optionalTime) assert.Error(t, err)