Skip to content

Commit 8c8696b

Browse files
authored
Merge pull request #47 from swistakm/fix/make-query-bindparam-play-along-with-x-go-type-skip-optional-pointer
fix: make BindQueryParameter play along with x-go-type-skip-optional-pointer
2 parents 46dbe22 + 4061fba commit 8c8696b

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

bindparam.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,10 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str
318318
// inner code will bind the string's value to this interface.
319319
var output interface{}
320320

321-
if required {
321+
// required params are never pointers, but it may happen that optional param
322+
// is not pointer as well if user decides to annotate it with
323+
// x-go-type-skip-optional-pointer
324+
if required || v.Kind() != reflect.Pointer {
322325
// If the parameter is required, then the generated code will pass us
323326
// a pointer to it: &int, &object, and so forth. We can directly set
324327
// them.
@@ -414,9 +417,10 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str
414417
if err != nil {
415418
return err
416419
}
417-
// If the parameter is required, and we've successfully unmarshaled
418-
// it, this assigns the new object to the pointer pointer.
419-
if !required {
420+
// If the parameter is required (or relies on x-go-type-skip-optional-pointer),
421+
// and we've successfully unmarshaled it, this assigns the new object to the
422+
// pointer pointer.
423+
if !required && k == reflect.Pointer {
420424
dv.Set(reflect.ValueOf(output))
421425
}
422426
return nil

bindparam_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,7 @@ func TestBindQueryParameter(t *testing.T) {
339339
queryParams := url.Values{
340340
"time": {"2020-12-09T16:09:53+00:00"},
341341
"number": {"100"},
342+
"text": {"loremipsum"},
342343
}
343344
// An optional time will be a pointer to a time in a parameter object
344345
var optionalTime *time.Time
@@ -351,6 +352,15 @@ func TestBindQueryParameter(t *testing.T) {
351352
require.NoError(t, err)
352353
assert.Nil(t, optionalNumber)
353354

355+
var optionalNonPointerText = ""
356+
err = BindQueryParameter("form", true, false, "notfound", queryParams, &optionalNonPointerText)
357+
require.NoError(t, err)
358+
assert.Zero(t, "")
359+
360+
err = BindQueryParameter("form", true, false, "text", queryParams, &optionalNonPointerText)
361+
require.NoError(t, err)
362+
assert.Equal(t, "loremipsum", optionalNonPointerText)
363+
354364
// If we require values, we require errors when they're not present.
355365
err = BindQueryParameter("form", true, true, "notfound", queryParams, &optionalTime)
356366
assert.Error(t, err)

0 commit comments

Comments
 (0)