From ef6ee34ee6a9666eb12141ba1feea25c516321d7 Mon Sep 17 00:00:00 2001 From: go165 <196723798+go165@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:41:47 +0800 Subject: [PATCH 1/3] fix: bind styled form arrays and JSON fields Share the form style defaults with the encoder, preserve legacy indexed keys, and bind JSON to the encoded field. Prepared with OpenAI Codex. --- bindform.go | 112 +++++++++++++++++++++++++++++------------------ bindform_test.go | 82 ++++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 43 deletions(-) diff --git a/bindform.go b/bindform.go index 10dfe39..595e55d 100644 --- a/bindform.go +++ b/bindform.go @@ -48,6 +48,9 @@ func BindMultipart(ptr interface{}, reader multipart.Reader) error { return BindForm(ptr, form.Value, form.File, nil) } +// BindForm populates a struct from decoded form values and multipart files. +// Encodings can describe styled arrays and JSON-valued fields. Fields without a +// value at their plain key also accept indexed or bracketed form keys. func BindForm(ptr interface{}, form map[string][]string, files map[string][]*multipart.FileHeader, encodings map[string]RequestBodyEncoding) error { ptrVal := reflect.Indirect(reflect.ValueOf(ptr)) if ptrVal.Kind() != reflect.Struct { @@ -62,48 +65,60 @@ func BindForm(ptr interface{}, form map[string][]string, files map[string][]*mul continue } tag = strings.Split(tag, ",")[0] // extract the name of the tag - if encoding, ok := encodings[tag]; ok { - // custom encoding - values := form[tag] - if len(values) == 0 { - continue - } - value := values[0] - if encoding.ContentType != "" { - if strings.HasPrefix(encoding.ContentType, jsonContentType) { - if err := JSONUnmarshal([]byte(value), ptr); err != nil { - return err - } - } - return errors.New("unsupported encoding, only application/json is supported") - } else { - var explode bool - if encoding.Explode != nil { - explode = *encoding.Explode - } - var required bool - if encoding.Required != nil { - required = *encoding.Required - } - if err := BindStyledParameterWithOptions(encoding.Style, tag, value, field.Addr().Interface(), BindStyledParameterOptions{ - ParamLocation: ParamLocationUndefined, - Explode: explode, - Required: required, - }); err != nil { - return err - } - } - } else { - // regular form data - if _, err := bindFormImpl(field, form, files, tag); err != nil { + if enc, ok := encodings[tag]; ok { + if err := bindEncodedFormField(field, form, files, tag, enc); err != nil { return err } + } else if _, err := bindFormImpl(field, form, files, tag); err != nil { + return err } } return nil } +func bindEncodedFormField(field reflect.Value, form url.Values, files map[string][]*multipart.FileHeader, name string, enc RequestBodyEncoding) error { + values := form[name] + if enc.ContentType == "" && enc.Required != nil && *enc.Required && len(values) > 0 && values[0] == "" { + return fmt.Errorf("parameter '%s' is empty, can't bind its value", name) + } + // Older clients use indexed and bracketed keys even for a property with an encoding. + if len(values) == 0 || (enc.ContentType == "" && enc.Style == "deepObject") { + _, err := bindFormImpl(field, form, files, name) + return err + } + if enc.ContentType != "" { + if !strings.HasPrefix(enc.ContentType, jsonContentType) { + return errors.New("unsupported encoding, only application/json is supported") + } + return JSONUnmarshal([]byte(values[0]), field.Addr().Interface()) + } + + style, explode := enc.Style, false + if enc.Style != "" || enc.Explode != nil { + style, explode = formStyleAndExplode(enc) + } + fieldType := field.Type() + for fieldType.Kind() == reflect.Pointer { + fieldType = fieldType.Elem() + } + separator := formStyleSeparator(style) + plainSlice := fieldType.Kind() == reflect.Slice && !reflect.PointerTo(fieldType).Implements(reflect.TypeFor[encoding.TextUnmarshaler]()) + if separator != "" && plainSlice { + if !explode { + values = strings.Split(values[0], separator) + } + _, err := bindFormImpl(field, url.Values{name: values}, nil, name) + return err + } + + return BindStyledParameterWithOptions(style, name, values[0], field.Addr().Interface(), BindStyledParameterOptions{ + ParamLocation: ParamLocationUndefined, + Explode: explode, + ValueIsUnescaped: true, + }) +} + // MarshalForm serializes a struct into application/x-www-form-urlencoded // values. // @@ -445,9 +460,7 @@ func marshalFormImpl(v reflect.Value, result url.Values, name string) { } } -// marshalFormStyled writes one top-level property according to the style and -// explode of its encoding. See MarshalForm. -func marshalFormStyled(v reflect.Value, result url.Values, name string, enc RequestBodyEncoding) error { +func formStyleAndExplode(enc RequestBodyEncoding) (string, bool) { style := enc.Style if style == "" { style = "form" @@ -456,20 +469,33 @@ func marshalFormStyled(v reflect.Value, result url.Values, name string, enc Requ if enc.Explode != nil { explode = *enc.Explode } + return style, explode +} - var separator string +func formStyleSeparator(style string) string { switch style { case "form": - separator = "," + return "," case "spaceDelimited": - separator = " " + return " " case "pipeDelimited": - separator = "|" - case "deepObject": + return "|" + default: + return "" + } +} + +// marshalFormStyled writes one top-level property according to the style and +// explode of its encoding. See MarshalForm. +func marshalFormStyled(v reflect.Value, result url.Values, name string, enc RequestBodyEncoding) error { + style, explode := formStyleAndExplode(enc) + if style == "deepObject" { // The bracketed default is the deepObject serialization. marshalFormImpl(v, result, name) return nil - default: + } + separator := formStyleSeparator(style) + if separator == "" { return fmt.Errorf("unsupported style '%s' for form property '%s'", style, name) } diff --git a/bindform_test.go b/bindform_test.go index 5077c8f..efc5aa2 100644 --- a/bindform_test.go +++ b/bindform_test.go @@ -68,6 +68,88 @@ func TestBindURLForm(t *testing.T) { } } +func TestBindFormEncodedArrays(t *testing.T) { + type body struct { + Topics []string `form:"topics" json:"renamedTopics"` + Counts *[]int `json:"counts,omitempty"` + } + explode, delimited := true, false + tests := []struct { + name string + encoding RequestBodyEncoding + topics []string + }{ + {"form defaults to exploded", RequestBodyEncoding{Style: "form"}, []string{"a+b", "7% off"}}, + {"explode alone implies form", RequestBodyEncoding{Explode: &explode}, []string{"a,b", "c d"}}, + {"form delimiter", RequestBodyEncoding{Style: "form", Explode: &delimited}, []string{"a b", "c"}}, + {"space delimiter", RequestBodyEncoding{Style: "spaceDelimited"}, []string{"a+b", "c"}}, + {"pipe delimiter", RequestBodyEncoding{Style: "pipeDelimited"}, []string{"a,b", "c"}}, + {"pipe exploded", RequestBodyEncoding{Style: "pipeDelimited", Explode: &explode}, []string{"a|b", "c"}}, + {"deepObject", RequestBodyEncoding{Style: "deepObject"}, []string{"a+b", "c"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + want := body{Topics: tt.topics, Counts: &[]int{3, 0, -8}} + encodings := map[string]RequestBodyEncoding{"topics": tt.encoding, "counts": tt.encoding} + values, err := MarshalForm(want, encodings) + require.NoError(t, err) + parsed, err := url.ParseQuery(values.Encode()) + require.NoError(t, err) + + var got body + require.NoError(t, BindForm(&got, parsed, nil, encodings)) + assert.Equal(t, want, got) + }) + } + + t.Run("indexed keys from existing clients", func(t *testing.T) { + want := body{Topics: []string{"news", "sports"}, Counts: &[]int{1, 2}} + legacy, err := MarshalForm(want, nil) + require.NoError(t, err) + encodings := map[string]RequestBodyEncoding{ + "topics": {Style: "form", Explode: &delimited}, + "counts": {Style: "pipeDelimited"}, + } + var got body + require.NoError(t, BindForm(&got, legacy, nil, encodings)) + assert.Equal(t, want, got) + }) +} + +func TestBindFormJSONEncodingTargetsField(t *testing.T) { + type filter struct { + Label string `json:"label"` + Age int `json:"age"` + } + type body struct { + Filter *filter `form:"search" json:"filter"` + Label string `json:"label"` + } + want := body{Filter: &filter{Label: "a+b", Age: 3}, Label: "body + 7%"} + encodings := map[string]RequestBodyEncoding{ + "search": {ContentType: "application/json; charset=utf-8"}, + "label": {Style: "form"}, + } + values, err := MarshalForm(want, encodings) + require.NoError(t, err) + parsed, err := url.ParseQuery(values.Encode()) + require.NoError(t, err) + var got body + require.NoError(t, BindForm(&got, parsed, nil, encodings)) + assert.Equal(t, want, got) +} + +func TestBindFormEncodingKeepsScalarTextDecoding(t *testing.T) { + type body struct { + Date types.Date `json:"date"` + } + required := true + encodings := map[string]RequestBodyEncoding{"date": {Required: &required}} + var got body + require.NoError(t, BindForm(&got, url.Values{"date": {"2026-12-02"}}, nil, encodings)) + assert.Equal(t, types.Date{Time: time.Date(2026, 12, 2, 0, 0, 0, 0, time.UTC)}, got.Date) +} + // TestBindURLFormNullable reproduces oapi-codegen/runtime#129: BindForm fails on // a nullable.Nullable[T] field because Nullable's underlying type is map[bool]T // and neither bindFormImpl nor BindStringToObjectWithOptions handles maps. From 07846349ad8abce5988cb0dadab248ad93d991fb Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Sat, 5 Dec 2026 07:29:51 -0800 Subject: [PATCH 2/3] fix: read form arrays in full under every encoding Three cases where BindForm read less of an array under an encoding than it does without one: - An entry which sets neither style nor explode rejected an array sent as repeated keys with "unhandled parameter style". It now leaves the default binding in place, as MarshalForm does. - A delimited (not exploded) array bound only the first value when a client repeated the key anyway. Every value is now split and bound. - An empty delimited array, which MarshalForm writes as an empty value, failed to parse for elements which are not strings. It now holds no elements. TestBindFormEncodedArrays becomes a matrix of every encoding an array can declare against every way a client may write the array, and TestMarshalFormEncoding reads each of its serializations back with BindForm. Co-Authored-By: Claude Fable 5.2 --- bindform.go | 17 ++++- bindform_test.go | 164 +++++++++++++++++++++++++++++++++++++---------- 2 files changed, 146 insertions(+), 35 deletions(-) diff --git a/bindform.go b/bindform.go index 595e55d..3d7f864 100644 --- a/bindform.go +++ b/bindform.go @@ -104,9 +104,24 @@ func bindEncodedFormField(field reflect.Value, form url.Values, files map[string } separator := formStyleSeparator(style) plainSlice := fieldType.Kind() == reflect.Slice && !reflect.PointerTo(fieldType).Implements(reflect.TypeFor[encoding.TextUnmarshaler]()) + if style == "" && plainSlice { + // An entry which sets neither style nor explode leaves the default in + // place, as it does in MarshalForm. + _, err := bindFormImpl(field, form, files, name) + return err + } if separator != "" && plainSlice { if !explode { - values = strings.Split(values[0], separator) + // A delimited array is a single value. A client which repeats the + // key anyway is still read in full, as it is without an encoding, + // and an empty value holds no elements. + var parts []string + for _, value := range values { + if value != "" { + parts = append(parts, strings.Split(value, separator)...) + } + } + values = parts } _, err := bindFormImpl(field, url.Values{name: values}, nil, name) return err diff --git a/bindform_test.go b/bindform_test.go index efc5aa2..9c999b7 100644 --- a/bindform_test.go +++ b/bindform_test.go @@ -4,6 +4,7 @@ import ( "bytes" "mime/multipart" "net/url" + "strings" "testing" "time" @@ -68,52 +69,122 @@ func TestBindURLForm(t *testing.T) { } } +// TestBindFormEncodedArrays is the bind half of oapi-codegen issue #2676 for +// arrays: under every encoding an array property can declare (the rows), every +// way a client may write the array (the columns) binds to the same value. func TestBindFormEncodedArrays(t *testing.T) { + // Topics is named by its form tag, which is also the key of its encoding. type body struct { Topics []string `form:"topics" json:"renamedTopics"` Counts *[]int `json:"counts,omitempty"` } - explode, delimited := true, false - tests := []struct { + yes, no := true, false + rows := []struct { name string encoding RequestBodyEncoding - topics []string + // delimiter separates the elements of an array which the encoding + // writes as a single value, and is empty for one which it does not. + delimiter string }{ - {"form defaults to exploded", RequestBodyEncoding{Style: "form"}, []string{"a+b", "7% off"}}, - {"explode alone implies form", RequestBodyEncoding{Explode: &explode}, []string{"a,b", "c d"}}, - {"form delimiter", RequestBodyEncoding{Style: "form", Explode: &delimited}, []string{"a b", "c"}}, - {"space delimiter", RequestBodyEncoding{Style: "spaceDelimited"}, []string{"a+b", "c"}}, - {"pipe delimiter", RequestBodyEncoding{Style: "pipeDelimited"}, []string{"a,b", "c"}}, - {"pipe exploded", RequestBodyEncoding{Style: "pipeDelimited", Explode: &explode}, []string{"a|b", "c"}}, - {"deepObject", RequestBodyEncoding{Style: "deepObject"}, []string{"a+b", "c"}}, + {name: "no style", encoding: RequestBodyEncoding{}}, + {name: "form", encoding: RequestBodyEncoding{Style: "form"}}, + {name: "form/explode", encoding: RequestBodyEncoding{Style: "form", Explode: &yes}}, + {name: "form/no explode", encoding: RequestBodyEncoding{Style: "form", Explode: &no}, delimiter: ","}, + {name: "explode alone", encoding: RequestBodyEncoding{Explode: &yes}}, + {name: "no explode alone", encoding: RequestBodyEncoding{Explode: &no}, delimiter: ","}, + {name: "spaceDelimited", encoding: RequestBodyEncoding{Style: "spaceDelimited"}, delimiter: " "}, + {name: "spaceDelimited/explode", encoding: RequestBodyEncoding{Style: "spaceDelimited", Explode: &yes}}, + {name: "spaceDelimited/no explode", encoding: RequestBodyEncoding{Style: "spaceDelimited", Explode: &no}, delimiter: " "}, + {name: "pipeDelimited", encoding: RequestBodyEncoding{Style: "pipeDelimited"}, delimiter: "|"}, + {name: "pipeDelimited/explode", encoding: RequestBodyEncoding{Style: "pipeDelimited", Explode: &yes}}, + {name: "pipeDelimited/no explode", encoding: RequestBodyEncoding{Style: "pipeDelimited", Explode: &no}, delimiter: "|"}, + {name: "deepObject", encoding: RequestBodyEncoding{Style: "deepObject"}}, + {name: "deepObject/explode", encoding: RequestBodyEncoding{Style: "deepObject", Explode: &yes}}, + {name: "json", encoding: RequestBodyEncoding{ContentType: "application/json"}}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - want := body{Topics: tt.topics, Counts: &[]int{3, 0, -8}} - encodings := map[string]RequestBodyEncoding{"topics": tt.encoding, "counts": tt.encoding} - values, err := MarshalForm(want, encodings) - require.NoError(t, err) - parsed, err := url.ParseQuery(values.Encode()) - require.NoError(t, err) - var got body - require.NoError(t, BindForm(&got, parsed, nil, encodings)) - assert.Equal(t, want, got) - }) - } + // The elements hold characters which form encoding escapes, and none + // which a style delimits by. + want := body{Topics: []string{"a+b", "7%off", "x&y=z"}, Counts: &[]int{3, 0, -8}} + counts := []string{"3", "0", "-8"} + + // MarshalForm's default, which is also what clients generated before + // encodings were honored send for every property. + indexed, err := MarshalForm(want, nil) + require.NoError(t, err) - t.Run("indexed keys from existing clients", func(t *testing.T) { - want := body{Topics: []string{"news", "sports"}, Counts: &[]int{1, 2}} - legacy, err := MarshalForm(want, nil) + // bind reads a body from values which have been over the wire. + bind := func(t *testing.T, values url.Values, encodings map[string]RequestBodyEncoding) (body, error) { + t.Helper() + parsed, err := url.ParseQuery(values.Encode()) require.NoError(t, err) - encodings := map[string]RequestBodyEncoding{ - "topics": {Style: "form", Explode: &delimited}, - "counts": {Style: "pipeDelimited"}, - } var got body - require.NoError(t, BindForm(&got, legacy, nil, encodings)) - assert.Equal(t, want, got) - }) + return got, BindForm(&got, parsed, nil, encodings) + } + + for _, row := range rows { + encodings := map[string]RequestBodyEncoding{"topics": row.encoding, "counts": row.encoding} + t.Run(row.name, func(t *testing.T) { + declared, err := MarshalForm(want, encodings) + require.NoError(t, err) + + columns := []struct { + name string + values url.Values + }{ + {"as declared", declared}, + {"indexed keys", indexed}, + {"bracketed keys", url.Values{"topics[]": want.Topics, "counts[]": counts}}, + } + if row.encoding.ContentType == "" { + // A JSON value can't be spread over several keys. Every other + // encoding reads repeated keys, as BindForm does without one, + // even where the array should have been a single value. + columns = append(columns, struct { + name string + values url.Values + }{"repeated keys", url.Values{"topics": want.Topics, "counts": counts}}) + } + for _, column := range columns { + t.Run(column.name, func(t *testing.T) { + got, err := bind(t, column.values, encodings) + require.NoError(t, err) + assert.Equal(t, want, got) + }) + } + + // A delimited array can't hold its own delimiter inside an + // element: values arrive decoded, so the element is split. Every + // other serialization keeps its elements whole. + t.Run("delimiters inside elements", func(t *testing.T) { + sent := body{Topics: []string{"a,b", "c d", "e|f"}} + values, err := MarshalForm(sent, encodings) + require.NoError(t, err) + got, err := bind(t, values, encodings) + require.NoError(t, err) + + expected := sent.Topics + if row.delimiter != "" { + expected = strings.Split(strings.Join(sent.Topics, row.delimiter), row.delimiter) + } + assert.Equal(t, expected, got.Topics) + }) + + // An empty array is written as an empty value when it is + // delimited, as [] in JSON and not at all otherwise. Each of + // those binds without an error, to an array with no elements. + t.Run("empty array", func(t *testing.T) { + values, err := MarshalForm(body{Topics: []string{}, Counts: &[]int{}}, encodings) + require.NoError(t, err) + got, err := bind(t, values, encodings) + require.NoError(t, err) + assert.Empty(t, got.Topics) + if got.Counts != nil { + assert.Empty(t, *got.Counts) + } + }) + }) + } } func TestBindFormJSONEncodingTargetsField(t *testing.T) { @@ -334,7 +405,8 @@ func TestMarshalForm(t *testing.T) { // TestMarshalFormEncoding covers oapi-codegen issue #2604: a property with an // encoding is serialized by its style and explode, rather than in the -// bracketed default. +// bracketed default. Each serialization is then read back by BindForm with +// the same encodings, which is the other half, oapi-codegen issue #2676. func TestMarshalFormEncoding(t *testing.T) { type object struct { Role string `json:"role"` @@ -357,6 +429,13 @@ func TestMarshalFormEncoding(t *testing.T) { body body encodings map[string]RequestBodyEncoding expected url.Values + // bound is what BindForm reads back, where that is not the body + // which was sent: a delimited array splits an element which holds + // its delimiter. + bound *body + // unbound marks a serialization which BindForm does not read back + // yet. Styled objects are the rest of oapi-codegen issue #2676. + unbound bool }{ { name: "no encoding keeps indexed keys", @@ -392,12 +471,14 @@ func TestMarshalFormEncoding(t *testing.T) { body: topics, encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &no}}, expected: url.Values{"email": {"jane@example.com"}, "topic": {"news,a,b c"}}, + bound: &body{Email: "jane@example.com", Topic: []string{"news", "a", "b c"}}, }, { name: "spaceDelimited does not explode by default", body: topics, encodings: map[string]RequestBodyEncoding{"topic": {Style: "spaceDelimited"}}, expected: url.Values{"email": {"jane@example.com"}, "topic": {"news a,b c"}}, + bound: &body{Email: "jane@example.com", Topic: []string{"news", "a,b", "c"}}, }, { name: "pipeDelimited", @@ -434,12 +515,14 @@ func TestMarshalFormEncoding(t *testing.T) { body: body{Object: &object{Role: "admin", Age: 3}, Map: map[string]string{"k": "v"}}, encodings: map[string]RequestBodyEncoding{"object": {Style: "form", Explode: &yes}, "map": {Style: "form"}}, expected: url.Values{"role": {"admin"}, "age": {"3"}, "k": {"v"}}, + unbound: true, }, { name: "object without explode", body: body{Object: &object{Role: "admin", Age: 3}, Map: map[string]string{"k": "v"}}, encodings: map[string]RequestBodyEncoding{"object": {Style: "form", Explode: &no}, "map": {Style: "form", Explode: &no}}, expected: url.Values{"object": {"age,3,role,admin"}, "map": {"k,v"}}, + unbound: true, }, { name: "json content type", @@ -453,6 +536,19 @@ func TestMarshalFormEncoding(t *testing.T) { marshaled, err := MarshalForm(tc.body, tc.encodings) require.NoError(t, err) assert.Equal(t, tc.expected, marshaled) + + if tc.unbound { + return + } + parsed, err := url.ParseQuery(marshaled.Encode()) + require.NoError(t, err) + want := tc.body + if tc.bound != nil { + want = *tc.bound + } + var got body + require.NoError(t, BindForm(&got, parsed, nil, tc.encodings)) + assert.Equal(t, want, got) }) } From ec1f5f6a14e59db67790e676cad2de81466b2e99 Mon Sep 17 00:00:00 2001 From: Marcin Romaszewicz Date: Sat, 5 Dec 2026 07:35:34 -0800 Subject: [PATCH 3/3] fix: bind single values and nullable properties under every encoding Two cases where a form property with an encoding was not read: - A property which is a single value, such as a date, was silently dropped under the deepObject style: every deepObject property went to the bracketed binder, which reads a struct as an object. Only arrays and objects go there now, and a single value is read as it is under any other style. - A nullable property failed under every style, and under an entry which sets none, because the styled binder took its wrapper, a map, for an object. The property is now classified by what the wrapper holds, so a nullable array is read as an array and a nullable value as a value. It also turns the panic for an `any` property under deepObject back into the error it is under the other styles. The array matrix gains a nullable array, and TestBindFormEncodedScalars is the same set of encodings against strings, integers, dates and UUIDs, whether required, optional or nullable. Co-Authored-By: Claude Fable 5.2 --- bindform.go | 43 +++++++++++---- bindform_test.go | 135 +++++++++++++++++++++++++++++++++++++---------- 2 files changed, 141 insertions(+), 37 deletions(-) diff --git a/bindform.go b/bindform.go index 3d7f864..53254c9 100644 --- a/bindform.go +++ b/bindform.go @@ -83,7 +83,7 @@ func bindEncodedFormField(field reflect.Value, form url.Values, files map[string return fmt.Errorf("parameter '%s' is empty, can't bind its value", name) } // Older clients use indexed and bracketed keys even for a property with an encoding. - if len(values) == 0 || (enc.ContentType == "" && enc.Style == "deepObject") { + if len(values) == 0 { _, err := bindFormImpl(field, form, files, name) return err } @@ -98,19 +98,38 @@ func bindEncodedFormField(field reflect.Value, form url.Values, files map[string if enc.Style != "" || enc.Explode != nil { style, explode = formStyleAndExplode(enc) } - fieldType := field.Type() - for fieldType.Kind() == reflect.Pointer { - fieldType = fieldType.Elem() + + // What a property is decides how its value is read. An array or an object + // has a serialization for each style, and anything else is a single value + // whatever the style. An optional pointer or a nullable wrapper around the + // property doesn't change which of those it is. + valueType, nullable := field.Type(), false + for { + switch { + case valueType.Kind() == reflect.Pointer: + valueType = valueType.Elem() + continue + case valueType.Kind() == reflect.Map && valueType.Key().Kind() == reflect.Bool: + valueType, nullable = valueType.Elem(), true + continue + } + break } + // A type which parses itself from text is a single value, whatever it is + // made of. + isText := reflect.PointerTo(valueType).Implements(reflect.TypeFor[encoding.TextUnmarshaler]()) + isArray := valueType.Kind() == reflect.Slice && !isText + isObject := (valueType.Kind() == reflect.Struct || valueType.Kind() == reflect.Map) && !isText + separator := formStyleSeparator(style) - plainSlice := fieldType.Kind() == reflect.Slice && !reflect.PointerTo(fieldType).Implements(reflect.TypeFor[encoding.TextUnmarshaler]()) - if style == "" && plainSlice { - // An entry which sets neither style nor explode leaves the default in - // place, as it does in MarshalForm. + switch { + case style == "deepObject" && (isArray || isObject), style == "" && isArray: + // deepObject is the bracketed default, and an entry which sets + // neither style nor explode leaves the default in place, as each + // does in MarshalForm. _, err := bindFormImpl(field, form, files, name) return err - } - if separator != "" && plainSlice { + case separator != "" && isArray: if !explode { // A delimited array is a single value. A client which repeats the // key anyway is still read in full, as it is without an encoding, @@ -125,6 +144,10 @@ func bindEncodedFormField(field reflect.Value, form url.Values, files map[string } _, err := bindFormImpl(field, url.Values{name: values}, nil, name) return err + case nullable && !isArray && !isObject: + // BindStringToObject reads the value and wraps it. The styled binder + // below would take the wrapper, which is a map, for an object. + return BindStringToObject(values[0], field.Addr().Interface()) } return BindStyledParameterWithOptions(style, name, values[0], field.Addr().Interface(), BindStyledParameterOptions{ diff --git a/bindform_test.go b/bindform_test.go index 9c999b7..2af9396 100644 --- a/bindform_test.go +++ b/bindform_test.go @@ -69,23 +69,21 @@ func TestBindURLForm(t *testing.T) { } } -// TestBindFormEncodedArrays is the bind half of oapi-codegen issue #2676 for -// arrays: under every encoding an array property can declare (the rows), every -// way a client may write the array (the columns) binds to the same value. -func TestBindFormEncodedArrays(t *testing.T) { - // Topics is named by its form tag, which is also the key of its encoding. - type body struct { - Topics []string `form:"topics" json:"renamedTopics"` - Counts *[]int `json:"counts,omitempty"` - } +// formEncodingRow is an encoding which a property of a form body can declare. +type formEncodingRow struct { + name string + encoding RequestBodyEncoding + // delimiter separates the elements of an array which the encoding + // writes as a single value, and is empty for one which it does not. + delimiter string +} + +// formEncodingRows is every one of them: each style with explode unset, on +// and off, the entry which sets neither, and a JSON content type. They are the +// rows of the bind half of oapi-codegen issue #2676, in the tests below. +func formEncodingRows() []formEncodingRow { yes, no := true, false - rows := []struct { - name string - encoding RequestBodyEncoding - // delimiter separates the elements of an array which the encoding - // writes as a single value, and is empty for one which it does not. - delimiter string - }{ + return []formEncodingRow{ {name: "no style", encoding: RequestBodyEncoding{}}, {name: "form", encoding: RequestBodyEncoding{Style: "form"}}, {name: "form/explode", encoding: RequestBodyEncoding{Style: "form", Explode: &yes}}, @@ -102,30 +100,53 @@ func TestBindFormEncodedArrays(t *testing.T) { {name: "deepObject/explode", encoding: RequestBodyEncoding{Style: "deepObject", Explode: &yes}}, {name: "json", encoding: RequestBodyEncoding{ContentType: "application/json"}}, } +} + +// TestBindFormEncodedArrays: under every encoding an array property can +// declare (the rows), every way a client may write the array (the columns) +// binds to the same value, whether the property is required, optional or +// nullable. +func TestBindFormEncodedArrays(t *testing.T) { + // Topics is named by its form tag, which is also the key of its encoding. + // Tags is the same array behind a nullable wrapper. + type body struct { + Topics []string `form:"topics" json:"renamedTopics"` + Counts *[]int `json:"counts,omitempty"` + Tags nullable.Nullable[[]string] `json:"tags,omitempty"` + } // The elements hold characters which form encoding escapes, and none // which a style delimits by. - want := body{Topics: []string{"a+b", "7%off", "x&y=z"}, Counts: &[]int{3, 0, -8}} + sent := body{Topics: []string{"a+b", "7%off", "x&y=z"}, Counts: &[]int{3, 0, -8}} counts := []string{"3", "0", "-8"} + want := sent + want.Tags = nullable.NewNullableWithValue(sent.Topics) // MarshalForm's default, which is also what clients generated before // encodings were honored send for every property. - indexed, err := MarshalForm(want, nil) + indexed, err := MarshalForm(sent, nil) require.NoError(t, err) // bind reads a body from values which have been over the wire. + // MarshalForm can't write a nullable property yet (runtime issue #202), + // so tags arrives as a copy of whatever was written for topics. bind := func(t *testing.T, values url.Values, encodings map[string]RequestBodyEncoding) (body, error) { t.Helper() parsed, err := url.ParseQuery(values.Encode()) require.NoError(t, err) + for key, value := range parsed { + if suffix, ok := strings.CutPrefix(key, "topics"); ok { + parsed["tags"+suffix] = value + } + } var got body return got, BindForm(&got, parsed, nil, encodings) } - for _, row := range rows { - encodings := map[string]RequestBodyEncoding{"topics": row.encoding, "counts": row.encoding} + for _, row := range formEncodingRows() { + encodings := map[string]RequestBodyEncoding{"topics": row.encoding, "counts": row.encoding, "tags": row.encoding} t.Run(row.name, func(t *testing.T) { - declared, err := MarshalForm(want, encodings) + declared, err := MarshalForm(sent, encodings) require.NoError(t, err) columns := []struct { @@ -134,7 +155,7 @@ func TestBindFormEncodedArrays(t *testing.T) { }{ {"as declared", declared}, {"indexed keys", indexed}, - {"bracketed keys", url.Values{"topics[]": want.Topics, "counts[]": counts}}, + {"bracketed keys", url.Values{"topics[]": sent.Topics, "counts[]": counts}}, } if row.encoding.ContentType == "" { // A JSON value can't be spread over several keys. Every other @@ -143,7 +164,7 @@ func TestBindFormEncodedArrays(t *testing.T) { columns = append(columns, struct { name string values url.Values - }{"repeated keys", url.Values{"topics": want.Topics, "counts": counts}}) + }{"repeated keys", url.Values{"topics": sent.Topics, "counts": counts}}) } for _, column := range columns { t.Run(column.name, func(t *testing.T) { @@ -157,17 +178,18 @@ func TestBindFormEncodedArrays(t *testing.T) { // element: values arrive decoded, so the element is split. Every // other serialization keeps its elements whole. t.Run("delimiters inside elements", func(t *testing.T) { - sent := body{Topics: []string{"a,b", "c d", "e|f"}} - values, err := MarshalForm(sent, encodings) + elements := []string{"a,b", "c d", "e|f"} + values, err := MarshalForm(body{Topics: elements}, encodings) require.NoError(t, err) got, err := bind(t, values, encodings) require.NoError(t, err) - expected := sent.Topics + expected := elements if row.delimiter != "" { - expected = strings.Split(strings.Join(sent.Topics, row.delimiter), row.delimiter) + expected = strings.Split(strings.Join(elements, row.delimiter), row.delimiter) } assert.Equal(t, expected, got.Topics) + assert.Equal(t, nullable.NewNullableWithValue(expected), got.Tags) }) // An empty array is written as an empty value when it is @@ -182,11 +204,70 @@ func TestBindFormEncodedArrays(t *testing.T) { if got.Counts != nil { assert.Empty(t, *got.Counts) } + if got.Tags.IsSpecified() { + assert.Empty(t, got.Tags.MustGet()) + } }) }) } } +// TestBindFormEncodedScalars: a property which is a single value is that +// value under every encoding (the rows), whatever its type and whether it is +// required, optional or nullable (the columns). A style only says how an +// array or an object is laid out. +func TestBindFormEncodedScalars(t *testing.T) { + type body struct { + Label string `json:"label,omitempty"` + Count *int `json:"count,omitempty"` + Day types.Date `json:"day,omitempty"` + OptDay *types.Date `json:"opt_day,omitempty"` + ID types.UUID `json:"id,omitempty"` + Note nullable.Nullable[string] `json:"note,omitempty"` + NullDay nullable.Nullable[types.Date] `json:"null_day,omitempty"` + } + count := -8 + day := types.Date{Time: time.Date(2026, 12, 2, 0, 0, 0, 0, time.UTC)} + id := types.UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} + + columns := []struct { + name string + key string + // value is the property as a form value, and json as the JSON an + // application/json encoding carries in its place. + value string + json string + want body + }{ + {"string", "label", "a+b 7%, c|d", `"a+b 7%, c|d"`, body{Label: "a+b 7%, c|d"}}, + {"optional integer", "count", "-8", `-8`, body{Count: &count}}, + {"date", "day", "2026-12-02", `"2026-12-02"`, body{Day: day}}, + {"optional date", "opt_day", "2026-12-02", `"2026-12-02"`, body{OptDay: &day}}, + {"uuid", "id", id.String(), `"` + id.String() + `"`, body{ID: id}}, + {"nullable string", "note", "x&y=z", `"x&y=z"`, body{Note: nullable.NewNullableWithValue("x&y=z")}}, + {"nullable date", "null_day", "2026-12-02", `"2026-12-02"`, body{NullDay: nullable.NewNullableWithValue(day)}}, + } + + for _, row := range formEncodingRows() { + t.Run(row.name, func(t *testing.T) { + for _, column := range columns { + t.Run(column.name, func(t *testing.T) { + value := column.value + if row.encoding.ContentType != "" { + value = column.json + } + parsed, err := url.ParseQuery(url.Values{column.key: {value}}.Encode()) + require.NoError(t, err) + + var got body + require.NoError(t, BindForm(&got, parsed, nil, map[string]RequestBodyEncoding{column.key: row.encoding})) + assert.Equal(t, column.want, got) + }) + } + }) + } +} + func TestBindFormJSONEncodingTargetsField(t *testing.T) { type filter struct { Label string `json:"label"`