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
150 changes: 107 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,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.
//
Expand Down Expand Up @@ -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"
Expand All @@ -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)
}

Expand Down
Loading