From ce5cd898b9eb50dca216e23d84e74c0f12fa2588 Mon Sep 17 00:00:00 2001 From: Max Brosnahan Date: Wed, 21 May 2025 08:17:15 +0200 Subject: [PATCH] Bind empty strings to nil pointers This allows pointers to be used for optional values in query, path and body params. --- bind.go | 4 ++++ bind_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/bind.go b/bind.go index 5940e15da..335aaac72 100644 --- a/bind.go +++ b/bind.go @@ -357,6 +357,10 @@ func unmarshalInputsToField(valueKind reflect.Kind, values []string, field refle func unmarshalInputToField(valueKind reflect.Kind, val string, field reflect.Value) (bool, error) { if valueKind == reflect.Ptr { + if val == "" { + field.Set(reflect.Zero(field.Type())) + return true, nil + } if field.IsNil() { field.Set(reflect.New(field.Type().Elem())) } diff --git a/bind_test.go b/bind_test.go index 303c8854a..790607715 100644 --- a/bind_test.go +++ b/bind_test.go @@ -1453,6 +1453,37 @@ func TestBindInt8(t *testing.T) { }) } +func TestBindPointer(t *testing.T) { + t.Run("nok, binding fails", func(t *testing.T) { + type target struct { + V *time.Time `query:"v"` + } + p := target{} + err := testBindURL("/?v=x", &p) + assert.EqualError(t, err, "code=400, message=parsing time \"x\" as \"2006-01-02T15:04:05Z07:00\": cannot parse \"x\" as \"2006\", internal=parsing time \"x\" as \"2006-01-02T15:04:05Z07:00\": cannot parse \"x\" as \"2006\"") + }) + + t.Run("ok, bind empty value to nil", func(t *testing.T) { + type target struct { + V *time.Time `query:"v"` + } + p := target{} + err := testBindURL("/?v=", &p) + assert.NoError(t, err) + assert.Nil(t, p.V) + }) + + t.Run("ok, binds to provided value", func(t *testing.T) { + type target struct { + V *time.Time `query:"v"` + } + p := target{} + err := testBindURL("/?v=2006-01-02T15:04:05Z", &p) + assert.NoError(t, err) + assert.Equal(t, "2006-01-02T15:04:05Z", p.V.Format(time.RFC3339)) + }) +} + func TestBindMultipartFormFiles(t *testing.T) { file1 := createTestFormFile("file", "file1.txt") file11 := createTestFormFile("file", "file11.txt")