Skip to content

Bind empty strings to nil pointers #2778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
}
Expand Down
31 changes: 31 additions & 0 deletions bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down