Skip to content

Commit

Permalink
fix: make BindQueryParameter play along with x-go-type-skip-optional-…
Browse files Browse the repository at this point in the history
…pointer
  • Loading branch information
swistakm committed Jul 9, 2024
1 parent 46dbe22 commit 4061fba
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
12 changes: 8 additions & 4 deletions bindparam.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions bindparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down

0 comments on commit 4061fba

Please sign in to comment.