diff --git a/bindform.go b/bindform.go index 10dfe39..53254c9 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,98 @@ 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 { + _, 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) + } + + // 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) + 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 + 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, + // 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 + 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{ + ParamLocation: ParamLocationUndefined, + Explode: explode, + ValueIsUnescaped: true, + }) +} + // MarshalForm serializes a struct into application/x-www-form-urlencoded // values. // @@ -445,9 +498,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 +507,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..2af9396 100644 --- a/bindform_test.go +++ b/bindform_test.go @@ -4,6 +4,7 @@ import ( "bytes" "mime/multipart" "net/url" + "strings" "testing" "time" @@ -68,6 +69,239 @@ func TestBindURLForm(t *testing.T) { } } +// 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 + return []formEncodingRow{ + {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"}}, + } +} + +// 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. + 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(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 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(sent, encodings) + require.NoError(t, err) + + columns := []struct { + name string + values url.Values + }{ + {"as declared", declared}, + {"indexed keys", indexed}, + {"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 + // 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": sent.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) { + 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 := elements + if 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 + // 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) + } + 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"` + 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. @@ -252,7 +486,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"` @@ -275,6 +510,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", @@ -310,12 +552,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", @@ -352,12 +596,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", @@ -371,6 +617,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) }) }