Skip to content

Commit 912bc9f

Browse files
authored
Merge pull request #48 from TelpeNight/fix-opt-query-params
Fix BindQueryParameter for optional parameters
2 parents 8c8696b + fb5c804 commit 912bc9f

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

bindparam.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,8 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str
321321
// required params are never pointers, but it may happen that optional param
322322
// is not pointer as well if user decides to annotate it with
323323
// x-go-type-skip-optional-pointer
324-
if required || v.Kind() != reflect.Pointer {
324+
var extraIndirect = !required && v.Kind() == reflect.Pointer
325+
if !extraIndirect {
325326
// If the parameter is required, then the generated code will pass us
326327
// a pointer to it: &int, &object, and so forth. We can directly set
327328
// them.
@@ -420,7 +421,7 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str
420421
// If the parameter is required (or relies on x-go-type-skip-optional-pointer),
421422
// and we've successfully unmarshaled it, this assigns the new object to the
422423
// pointer pointer.
423-
if !required && k == reflect.Pointer {
424+
if extraIndirect {
424425
dv.Set(reflect.ValueOf(output))
425426
}
426427
return nil
@@ -460,7 +461,7 @@ func BindQueryParameter(style string, explode bool, required bool, paramName str
460461
if err != nil {
461462
return err
462463
}
463-
if !required {
464+
if extraIndirect {
464465
dv.Set(reflect.ValueOf(output))
465466
}
466467
return nil

bindparam_test.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ func TestBindQueryParameter(t *testing.T) {
355355
var optionalNonPointerText = ""
356356
err = BindQueryParameter("form", true, false, "notfound", queryParams, &optionalNonPointerText)
357357
require.NoError(t, err)
358-
assert.Zero(t, "")
358+
assert.Zero(t, optionalNonPointerText)
359359

360360
err = BindQueryParameter("form", true, false, "text", queryParams, &optionalNonPointerText)
361361
require.NoError(t, err)
@@ -367,6 +367,15 @@ func TestBindQueryParameter(t *testing.T) {
367367
err = BindQueryParameter("form", true, true, "notfound", queryParams, &optionalNumber)
368368
assert.Error(t, err)
369369

370+
var optionalPointerText *string
371+
err = BindQueryParameter("form", true, false, "notfound", queryParams, &optionalPointerText)
372+
require.NoError(t, err)
373+
assert.Zero(t, optionalPointerText)
374+
375+
err = BindQueryParameter("form", true, false, "text", queryParams, &optionalPointerText)
376+
require.NoError(t, err)
377+
require.NotNil(t, optionalPointerText)
378+
assert.Equal(t, "loremipsum", *optionalPointerText)
370379
})
371380
}
372381

0 commit comments

Comments
 (0)