diff --git a/binding/form_mapping.go b/binding/form_mapping.go index 6982fd4f..de19fac7 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -328,8 +328,8 @@ func setWithProperType(val string, value reflect.Value, field reflect.StructFiel return err } - // If it is a string type, no spaces are removed, and the user data is not modified here - if value.Kind() != reflect.String { + // Preserve string whitespace; defer pointers until their element type is known. + if value.Kind() != reflect.String && value.Kind() != reflect.Ptr { val = strings.TrimSpace(val) } diff --git a/binding/form_mapping_test.go b/binding/form_mapping_test.go index c78f7398..1ee25419 100644 --- a/binding/form_mapping_test.go +++ b/binding/form_mapping_test.go @@ -23,6 +23,9 @@ func TestMappingBaseTypes(t *testing.T) { intPtr := func(i int) *int { return &i } + text := " \ttest\n " + textPtr := &text + whitespace := " \t\n " for _, tt := range []struct { name string value any @@ -45,6 +48,14 @@ func TestMappingBaseTypes(t *testing.T) { {"base type", struct{ F string }{}, "test", string("test")}, {"base type", struct{ F *int }{}, "9", intPtr(9)}, + // Preserve string whitespace through collection element pointers. + {"whitespace", struct{ F []*string }{}, text, []*string{&text}}, + {"whitespace", struct{ F [1]*string }{}, text, [1]*string{&text}}, + {"whitespace", struct{ F []**string }{}, text, []**string{&textPtr}}, + {"whitespace only", struct{ F []*string }{}, whitespace, []*string{&whitespace}}, + {"whitespace only", struct{ F [1]*string }{}, whitespace, [1]*string{&whitespace}}, + {"whitespace", struct{ F []*int }{}, " \t9\n ", []*int{intPtr(9)}}, + // zero values {"zero value", struct{ F int }{}, "", int(0)}, {"zero value", struct{ F uint }{}, "", uint(0)},