Skip to content

Commit c67d5d3

Browse files
mromaszewiczclaude
andauthored
fix: honour style and explode in MarshalForm encodings (#187)
MarshalForm only read ContentType from a property's encoding, so an array was always written with indexed keys (topic[0]=a&topic[1]=b), even when the encoding declared style: form, explode: true, which serializes as repeated keys (topic=a&topic=b). A property whose encoding sets Style or Explode is now serialized as a query parameter of that style would be: form, spaceDelimited and pipeDelimited repeat the key when exploded and write one delimited value otherwise, and deepObject is the bracketed default. Explode defaults to true for form and false otherwise, as in the specification. Properties with no encoding, or one that sets neither field, are unchanged. Also fix the ContentType branch, which returned "unsupported encoding" for application/json too and marshaled the reflect.Value rather than the value it holds. Fixes #186 Refs oapi-codegen/oapi-codegen#2604 Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 44fd220 commit c67d5d3

3 files changed

Lines changed: 328 additions & 16 deletions

File tree

‎bindform.go‎

Lines changed: 153 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package runtime
22

33
import (
4+
"bytes"
5+
"encoding"
6+
"encoding/json"
47
"errors"
58
"fmt"
69
"mime/multipart"
@@ -101,6 +104,24 @@ func BindForm(ptr interface{}, form map[string][]string, files map[string][]*mul
101104
return nil
102105
}
103106

107+
// MarshalForm serializes a struct into application/x-www-form-urlencoded
108+
// values.
109+
//
110+
// Properties are written in bracketed form by default: an array becomes
111+
// name[0]=a&name[1]=b and a nested object becomes name[key]=value. A property
112+
// with an entry in encodings follows that entry instead, mirroring the OpenAPI
113+
// Encoding Object:
114+
//
115+
// - ContentType: the value is serialized as a single field in that media
116+
// type. Only application/json is supported.
117+
// - Style and Explode: arrays and flat objects are serialized as a query
118+
// parameter of that style would be. "form" (the default when only Explode
119+
// is set), "spaceDelimited" and "pipeDelimited" write repeated keys
120+
// (name=a&name=b) when exploded and one delimited value (name=a,b)
121+
// otherwise; "deepObject" is the bracketed default. Explode defaults to
122+
// true for "form" and false for the other styles, as in the specification.
123+
//
124+
// An entry which sets none of those leaves the default in place.
104125
func MarshalForm(ptr interface{}, encodings map[string]RequestBodyEncoding) (url.Values, error) {
105126
ptrVal := reflect.Indirect(reflect.ValueOf(ptr))
106127
if ptrVal.Kind() != reflect.Struct {
@@ -119,16 +140,25 @@ func MarshalForm(ptr interface{}, encodings map[string]RequestBodyEncoding) (url
119140
continue
120141
}
121142
tag = strings.Split(tag, ",")[0] // extract the name of the tag
122-
if encoding, ok := encodings[tag]; ok && encoding.ContentType != "" {
123-
if strings.HasPrefix(encoding.ContentType, jsonContentType) {
124-
if data, err := JSONMarshal(field); err != nil { //nolint:staticcheck
125-
return nil, err
126-
} else {
127-
result[tag] = append(result[tag], string(data))
128-
}
143+
encoding, hasEncoding := encodings[tag]
144+
switch {
145+
case hasEncoding && encoding.ContentType != "":
146+
if !strings.HasPrefix(encoding.ContentType, jsonContentType) {
147+
return nil, errors.New("unsupported encoding, only application/json is supported")
129148
}
130-
return nil, errors.New("unsupported encoding, only application/json is supported")
131-
} else {
149+
if (field.Kind() == reflect.Pointer || field.Kind() == reflect.Interface) && field.IsNil() {
150+
continue
151+
}
152+
data, err := JSONMarshal(field.Interface())
153+
if err != nil {
154+
return nil, err
155+
}
156+
result[tag] = append(result[tag], string(data))
157+
case hasEncoding && (encoding.Style != "" || encoding.Explode != nil):
158+
if err := marshalFormStyled(field, result, tag, encoding); err != nil {
159+
return nil, err
160+
}
161+
default:
132162
marshalFormImpl(field, result, tag)
133163
}
134164
}
@@ -414,3 +444,117 @@ func marshalFormImpl(v reflect.Value, result url.Values, name string) {
414444
result[name] = append(result[name], fmt.Sprint(v.Interface()))
415445
}
416446
}
447+
448+
// marshalFormStyled writes one top-level property according to the style and
449+
// explode of its encoding. See MarshalForm.
450+
func marshalFormStyled(v reflect.Value, result url.Values, name string, enc RequestBodyEncoding) error {
451+
style := enc.Style
452+
if style == "" {
453+
style = "form"
454+
}
455+
explode := style == "form"
456+
if enc.Explode != nil {
457+
explode = *enc.Explode
458+
}
459+
460+
var separator string
461+
switch style {
462+
case "form":
463+
separator = ","
464+
case "spaceDelimited":
465+
separator = " "
466+
case "pipeDelimited":
467+
separator = "|"
468+
case "deepObject":
469+
// The bracketed default is the deepObject serialization.
470+
marshalFormImpl(v, result, name)
471+
return nil
472+
default:
473+
return fmt.Errorf("unsupported style '%s' for form property '%s'", style, name)
474+
}
475+
476+
for v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface {
477+
if v.IsNil() {
478+
return nil
479+
}
480+
v = v.Elem()
481+
}
482+
value := v.Interface()
483+
484+
// Types which serialize to a single string are primitives, whatever
485+
// their kind.
486+
if str, ok := marshalKnownTypes(value); ok {
487+
result[name] = append(result[name], str)
488+
return nil
489+
}
490+
if tm, ok := value.(encoding.TextMarshaler); ok {
491+
b, err := tm.MarshalText()
492+
if err != nil {
493+
return fmt.Errorf("error marshaling '%s' as text: %w", name, err)
494+
}
495+
result[name] = append(result[name], string(b))
496+
return nil
497+
}
498+
499+
var fieldDict map[string]string
500+
var err error
501+
switch v.Kind() {
502+
case reflect.Slice:
503+
parts := make([]string, v.Len())
504+
for i := range parts {
505+
if parts[i], err = primitiveToString(v.Index(i).Interface()); err != nil {
506+
return fmt.Errorf("error formatting '%s': %w", name, err)
507+
}
508+
}
509+
if explode {
510+
result[name] = append(result[name], parts...)
511+
} else {
512+
result[name] = append(result[name], strings.Join(parts, separator))
513+
}
514+
return nil
515+
case reflect.Struct:
516+
// A struct with a Marshaler, such as one with additional properties,
517+
// is styled from its JSON form.
518+
if m, ok := value.(json.Marshaler); ok {
519+
buf, err := m.MarshalJSON()
520+
if err != nil {
521+
return fmt.Errorf("failed to marshal '%s' to JSON: %w", name, err)
522+
}
523+
d := json.NewDecoder(bytes.NewReader(buf))
524+
d.UseNumber()
525+
var decoded interface{}
526+
if err := d.Decode(&decoded); err != nil {
527+
return fmt.Errorf("failed to unmarshal JSON for '%s': %w", name, err)
528+
}
529+
return marshalFormStyled(reflect.ValueOf(&decoded).Elem(), result, name, enc)
530+
}
531+
fieldDict, err = structFieldDict(name, value)
532+
case reflect.Map:
533+
fieldDict, err = mapFieldDict(name, value)
534+
default:
535+
str, err := primitiveToString(value)
536+
if err != nil {
537+
return fmt.Errorf("error formatting '%s': %w", name, err)
538+
}
539+
result[name] = append(result[name], str)
540+
return nil
541+
}
542+
if err != nil {
543+
return err
544+
}
545+
546+
// An exploded object contributes each property as a field of its own.
547+
keys := sortedKeys(fieldDict)
548+
if explode {
549+
for _, k := range keys {
550+
result[k] = append(result[k], fieldDict[k])
551+
}
552+
return nil
553+
}
554+
parts := make([]string, 0, 2*len(keys))
555+
for _, k := range keys {
556+
parts = append(parts, k, fieldDict[k])
557+
}
558+
result[name] = append(result[name], strings.Join(parts, separator))
559+
return nil
560+
}

‎bindform_test.go‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"mime/multipart"
66
"net/url"
77
"testing"
8+
"time"
89

910
"github.com/oapi-codegen/nullable"
1011
"github.com/oapi-codegen/runtime/types"
@@ -249,6 +250,156 @@ func TestMarshalForm(t *testing.T) {
249250
}
250251
}
251252

253+
// TestMarshalFormEncoding covers oapi-codegen issue #2604: a property with an
254+
// encoding is serialized by its style and explode, rather than in the
255+
// bracketed default.
256+
func TestMarshalFormEncoding(t *testing.T) {
257+
type object struct {
258+
Role string `json:"role"`
259+
Age int `json:"age"`
260+
}
261+
type body struct {
262+
Email string `json:"email,omitempty"`
263+
Topic []string `json:"topic,omitempty"`
264+
OptTopic *[]int `json:"opt_topic,omitempty"`
265+
Object *object `json:"object,omitempty"`
266+
Map map[string]string `json:"map,omitempty"`
267+
When *types.Date `json:"when,omitempty"`
268+
}
269+
yes, no := true, false
270+
topics := body{Email: "jane@example.com", Topic: []string{"news", "a,b c"}}
271+
date := types.Date{Time: time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC)}
272+
273+
testCases := []struct {
274+
name string
275+
body body
276+
encodings map[string]RequestBodyEncoding
277+
expected url.Values
278+
}{
279+
{
280+
name: "no encoding keeps indexed keys",
281+
body: topics,
282+
expected: url.Values{"email": {"jane@example.com"}, "topic[0]": {"news"}, "topic[1]": {"a,b c"}},
283+
},
284+
{
285+
name: "encoding without style or explode keeps indexed keys",
286+
body: topics,
287+
encodings: map[string]RequestBodyEncoding{"topic": {Required: &yes}},
288+
expected: url.Values{"email": {"jane@example.com"}, "topic[0]": {"news"}, "topic[1]": {"a,b c"}},
289+
},
290+
{
291+
name: "form explode repeats the key",
292+
body: topics,
293+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &yes}},
294+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
295+
},
296+
{
297+
name: "form explodes by default",
298+
body: topics,
299+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form"}},
300+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
301+
},
302+
{
303+
name: "explode alone implies form",
304+
body: topics,
305+
encodings: map[string]RequestBodyEncoding{"topic": {Explode: &yes}},
306+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
307+
},
308+
{
309+
name: "form without explode joins with commas",
310+
body: topics,
311+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &no}},
312+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news,a,b c"}},
313+
},
314+
{
315+
name: "spaceDelimited does not explode by default",
316+
body: topics,
317+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "spaceDelimited"}},
318+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news a,b c"}},
319+
},
320+
{
321+
name: "pipeDelimited",
322+
body: topics,
323+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "pipeDelimited", Explode: &no}},
324+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news|a,b c"}},
325+
},
326+
{
327+
name: "pipeDelimited explode repeats the key",
328+
body: topics,
329+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "pipeDelimited", Explode: &yes}},
330+
expected: url.Values{"email": {"jane@example.com"}, "topic": {"news", "a,b c"}},
331+
},
332+
{
333+
name: "deepObject is the bracketed default",
334+
body: body{Topic: []string{"news"}, Object: &object{Role: "admin", Age: 3}},
335+
encodings: map[string]RequestBodyEncoding{"topic": {Style: "deepObject", Explode: &yes}, "object": {Style: "deepObject", Explode: &yes}},
336+
expected: url.Values{"topic[0]": {"news"}, "object[role]": {"admin"}, "object[age]": {"3"}},
337+
},
338+
{
339+
name: "optional array",
340+
body: body{OptTopic: &[]int{1, 2}},
341+
encodings: map[string]RequestBodyEncoding{"opt_topic": {Style: "form", Explode: &yes}},
342+
expected: url.Values{"opt_topic": {"1", "2"}},
343+
},
344+
{
345+
name: "primitive",
346+
body: body{Email: "jane@example.com", When: &date},
347+
encodings: map[string]RequestBodyEncoding{"email": {Style: "form", Explode: &yes}, "when": {Style: "form"}},
348+
expected: url.Values{"email": {"jane@example.com"}, "when": {"2026-11-20"}},
349+
},
350+
{
351+
name: "exploded object contributes its properties",
352+
body: body{Object: &object{Role: "admin", Age: 3}, Map: map[string]string{"k": "v"}},
353+
encodings: map[string]RequestBodyEncoding{"object": {Style: "form", Explode: &yes}, "map": {Style: "form"}},
354+
expected: url.Values{"role": {"admin"}, "age": {"3"}, "k": {"v"}},
355+
},
356+
{
357+
name: "object without explode",
358+
body: body{Object: &object{Role: "admin", Age: 3}, Map: map[string]string{"k": "v"}},
359+
encodings: map[string]RequestBodyEncoding{"object": {Style: "form", Explode: &no}, "map": {Style: "form", Explode: &no}},
360+
expected: url.Values{"object": {"age,3,role,admin"}, "map": {"k,v"}},
361+
},
362+
{
363+
name: "json content type",
364+
body: body{Topic: []string{"news"}, Object: &object{Role: "admin", Age: 3}},
365+
encodings: map[string]RequestBodyEncoding{"object": {ContentType: "application/json"}},
366+
expected: url.Values{"topic[0]": {"news"}, "object": {`{"role":"admin","age":3}`}},
367+
},
368+
}
369+
for _, tc := range testCases {
370+
t.Run(tc.name, func(t *testing.T) {
371+
marshaled, err := MarshalForm(tc.body, tc.encodings)
372+
require.NoError(t, err)
373+
assert.Equal(t, tc.expected, marshaled)
374+
})
375+
}
376+
377+
t.Run("wire format", func(t *testing.T) {
378+
marshaled, err := MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {Style: "form", Explode: &yes}})
379+
require.NoError(t, err)
380+
assert.Equal(t, "email=jane%40example.com&topic=news&topic=a%2Cb+c", marshaled.Encode())
381+
382+
// What we send is what BindForm reads back.
383+
var bound body
384+
require.NoError(t, BindForm(&bound, marshaled, nil, nil))
385+
assert.Equal(t, topics, bound)
386+
})
387+
388+
t.Run("errors", func(t *testing.T) {
389+
_, err := MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {Style: "matrix"}})
390+
assert.ErrorContains(t, err, "unsupported style 'matrix'")
391+
392+
_, err = MarshalForm(topics, map[string]RequestBodyEncoding{"topic": {ContentType: "text/csv"}})
393+
assert.ErrorContains(t, err, "unsupported encoding")
394+
395+
type nested struct {
396+
Objects []object `json:"objects"`
397+
}
398+
_, err = MarshalForm(nested{Objects: []object{{}}}, map[string]RequestBodyEncoding{"objects": {Style: "form"}})
399+
assert.Error(t, err)
400+
})
401+
}
402+
252403
type fileData struct {
253404
field string
254405
filename string

0 commit comments

Comments
 (0)