Skip to content
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
112 changes: 69 additions & 43 deletions bindform.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
//
Expand Down Expand Up @@ -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"
Expand All @@ -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)
}

Expand Down
82 changes: 82 additions & 0 deletions bindform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down