Skip to content
Merged
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
162 changes: 153 additions & 9 deletions bindform.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package runtime

import (
"bytes"
"encoding"
"encoding/json"
"errors"
"fmt"
"mime/multipart"
Expand Down Expand Up @@ -101,6 +104,24 @@ func BindForm(ptr interface{}, form map[string][]string, files map[string][]*mul
return nil
}

// MarshalForm serializes a struct into application/x-www-form-urlencoded
// values.
//
// Properties are written in bracketed form by default: an array becomes
// name[0]=a&name[1]=b and a nested object becomes name[key]=value. A property
// with an entry in encodings follows that entry instead, mirroring the OpenAPI
// Encoding Object:
//
// - ContentType: the value is serialized as a single field in that media
// type. Only application/json is supported.
// - Style and Explode: arrays and flat objects are serialized as a query
// parameter of that style would be. "form" (the default when only Explode
// is set), "spaceDelimited" and "pipeDelimited" write repeated keys
// (name=a&name=b) when exploded and one delimited value (name=a,b)
// otherwise; "deepObject" is the bracketed default. Explode defaults to
// true for "form" and false for the other styles, as in the specification.
//
// An entry which sets none of those leaves the default in place.
func MarshalForm(ptr interface{}, encodings map[string]RequestBodyEncoding) (url.Values, error) {
ptrVal := reflect.Indirect(reflect.ValueOf(ptr))
if ptrVal.Kind() != reflect.Struct {
Expand All @@ -119,16 +140,25 @@ func MarshalForm(ptr interface{}, encodings map[string]RequestBodyEncoding) (url
continue
}
tag = strings.Split(tag, ",")[0] // extract the name of the tag
if encoding, ok := encodings[tag]; ok && encoding.ContentType != "" {
if strings.HasPrefix(encoding.ContentType, jsonContentType) {
if data, err := JSONMarshal(field); err != nil { //nolint:staticcheck
return nil, err
} else {
result[tag] = append(result[tag], string(data))
}
encoding, hasEncoding := encodings[tag]
switch {
case hasEncoding && encoding.ContentType != "":
if !strings.HasPrefix(encoding.ContentType, jsonContentType) {
return nil, errors.New("unsupported encoding, only application/json is supported")
}
return nil, errors.New("unsupported encoding, only application/json is supported")
} else {
if (field.Kind() == reflect.Pointer || field.Kind() == reflect.Interface) && field.IsNil() {
continue
}
data, err := JSONMarshal(field.Interface())
if err != nil {
return nil, err
}
result[tag] = append(result[tag], string(data))
case hasEncoding && (encoding.Style != "" || encoding.Explode != nil):
if err := marshalFormStyled(field, result, tag, encoding); err != nil {
return nil, err
}
default:
marshalFormImpl(field, result, tag)
}
}
Expand Down Expand Up @@ -414,3 +444,117 @@ func marshalFormImpl(v reflect.Value, result url.Values, name string) {
result[name] = append(result[name], fmt.Sprint(v.Interface()))
}
}

// 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 := enc.Style
if style == "" {
style = "form"
}
explode := style == "form"
if enc.Explode != nil {
explode = *enc.Explode
}

var separator string
switch style {
case "form":
separator = ","
case "spaceDelimited":
separator = " "
case "pipeDelimited":
separator = "|"
case "deepObject":
// The bracketed default is the deepObject serialization.
marshalFormImpl(v, result, name)
return nil
default:
return fmt.Errorf("unsupported style '%s' for form property '%s'", style, name)
}

for v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface {
if v.IsNil() {
return nil
}
v = v.Elem()
}
value := v.Interface()

// Types which serialize to a single string are primitives, whatever
// their kind.
if str, ok := marshalKnownTypes(value); ok {
result[name] = append(result[name], str)
return nil
}
if tm, ok := value.(encoding.TextMarshaler); ok {
b, err := tm.MarshalText()
if err != nil {
return fmt.Errorf("error marshaling '%s' as text: %w", name, err)
}
result[name] = append(result[name], string(b))
return nil
}

var fieldDict map[string]string
var err error
switch v.Kind() {
case reflect.Slice:
parts := make([]string, v.Len())
for i := range parts {
if parts[i], err = primitiveToString(v.Index(i).Interface()); err != nil {
return fmt.Errorf("error formatting '%s': %w", name, err)
}
}
if explode {
result[name] = append(result[name], parts...)
} else {
result[name] = append(result[name], strings.Join(parts, separator))
}
return nil
case reflect.Struct:
// A struct with a Marshaler, such as one with additional properties,
// is styled from its JSON form.
if m, ok := value.(json.Marshaler); ok {
buf, err := m.MarshalJSON()
if err != nil {
return fmt.Errorf("failed to marshal '%s' to JSON: %w", name, err)
}
d := json.NewDecoder(bytes.NewReader(buf))
d.UseNumber()
var decoded interface{}
if err := d.Decode(&decoded); err != nil {
return fmt.Errorf("failed to unmarshal JSON for '%s': %w", name, err)
}
return marshalFormStyled(reflect.ValueOf(&decoded).Elem(), result, name, enc)
}
fieldDict, err = structFieldDict(name, value)
case reflect.Map:
fieldDict, err = mapFieldDict(name, value)
default:
str, err := primitiveToString(value)
if err != nil {
return fmt.Errorf("error formatting '%s': %w", name, err)
}
result[name] = append(result[name], str)
return nil
}
if err != nil {
return err
}

// An exploded object contributes each property as a field of its own.
keys := sortedKeys(fieldDict)
if explode {
for _, k := range keys {
result[k] = append(result[k], fieldDict[k])
}
return nil
}
parts := make([]string, 0, 2*len(keys))
for _, k := range keys {
parts = append(parts, k, fieldDict[k])
}
result[name] = append(result[name], strings.Join(parts, separator))
return nil
}
151 changes: 151 additions & 0 deletions bindform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"mime/multipart"
"net/url"
"testing"
"time"

"github.com/oapi-codegen/nullable"
"github.com/oapi-codegen/runtime/types"
Expand Down Expand Up @@ -249,6 +250,156 @@ 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.
func TestMarshalFormEncoding(t *testing.T) {
type object struct {
Role string `json:"role"`
Age int `json:"age"`
}
type body struct {
Email string `json:"email,omitempty"`
Topic []string `json:"topic,omitempty"`
OptTopic *[]int `json:"opt_topic,omitempty"`
Object *object `json:"object,omitempty"`
Map map[string]string `json:"map,omitempty"`
When *types.Date `json:"when,omitempty"`
}
yes, no := true, false
topics := body{Email: "jane@example.com", Topic: []string{"news", "a,b c"}}
date := types.Date{Time: time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC)}

testCases := []struct {
name string
body body
encodings map[string]RequestBodyEncoding
expected url.Values
}{
{
name: "no encoding keeps indexed keys",
body: topics,
expected: url.Values{"email": {"jane@example.com"}, "topic[0]": {"news"}, "topic[1]": {"a,b c"}},
},
{
name: "encoding without style or explode keeps indexed keys",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Required: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic[0]": {"news"}, "topic[1]": {"a,b c"}},
},
{
name: "form explode repeats the key",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "form explodes by default",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form"}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "explode alone implies form",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Explode: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "form without explode joins with commas",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &no}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"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"}},
},
{
name: "pipeDelimited",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "pipeDelimited", Explode: &no}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news|a,b c"}},
},
{
name: "pipeDelimited explode repeats the key",
body: topics,
encodings: map[string]RequestBodyEncoding{"topic": {Style: "pipeDelimited", Explode: &yes}},
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
},
{
name: "deepObject is the bracketed default",
body: body{Topic: []string{"news"}, Object: &object{Role: "admin", Age: 3}},
encodings: map[string]RequestBodyEncoding{"topic": {Style: "deepObject", Explode: &yes}, "object": {Style: "deepObject", Explode: &yes}},
expected: url.Values{"topic[0]": {"news"}, "object[role]": {"admin"}, "object[age]": {"3"}},
},
{
name: "optional array",
body: body{OptTopic: &[]int{1, 2}},
encodings: map[string]RequestBodyEncoding{"opt_topic": {Style: "form", Explode: &yes}},
expected: url.Values{"opt_topic": {"1", "2"}},
},
{
name: "primitive",
body: body{Email: "jane@example.com", When: &date},
encodings: map[string]RequestBodyEncoding{"email": {Style: "form", Explode: &yes}, "when": {Style: "form"}},
expected: url.Values{"email": {"jane@example.com"}, "when": {"2026-11-20"}},
},
{
name: "exploded object contributes its properties",
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"}},
},
{
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"}},
},
{
name: "json content type",
body: body{Topic: []string{"news"}, Object: &object{Role: "admin", Age: 3}},
encodings: map[string]RequestBodyEncoding{"object": {ContentType: "application/json"}},
expected: url.Values{"topic[0]": {"news"}, "object": {`{"role":"admin","age":3}`}},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
marshaled, err := MarshalForm(tc.body, tc.encodings)
require.NoError(t, err)
assert.Equal(t, tc.expected, marshaled)
})
}

t.Run("wire format", func(t *testing.T) {
marshaled, err := MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &yes}})
require.NoError(t, err)
assert.Equal(t, "email=jane%40example.com&topic=news&topic=a%2Cb+c", marshaled.Encode())

// What we send is what BindForm reads back.
var bound body
require.NoError(t, BindForm(&bound, marshaled, nil, nil))
assert.Equal(t, topics, bound)
})

t.Run("errors", func(t *testing.T) {
_, err := MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {Style: "matrix"}})
assert.ErrorContains(t, err, "unsupported style 'matrix'")

_, err = MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {ContentType: "text/csv"}})
assert.ErrorContains(t, err, "unsupported encoding")

type nested struct {
Objects []object `json:"objects"`
}
_, err = MarshalForm(nested{Objects: []object{{}}}, map[string]RequestBodyEncoding{"objects": {Style: "form"}})
assert.Error(t, err)
})
}

type fileData struct {
field string
filename string
Expand Down
Loading