Documentation
¶
Overview ¶
Package form implements encoding and decoding of application/x-www-form-urlencoded data.
Errors returned by the Decode and Encode functions are of type *Error, which records the operation (Op) that failed and, via Unwrap, any underlying cause such as an error from a TextMarshaler or TextUnmarshaler. Use errors.As to inspect them; the Error message text is unchanged from earlier versions.
Index ¶
- func DecodeString(dst interface{}, src string) error
- func DecodeValues(dst interface{}, vs url.Values) error
- func EncodeToString(dst interface{}, needEmptyValue ...bool) (string, error)
- func EncodeToStringWith(dst interface{}, d rune, e rune, z bool) (string, error)
- func EncodeToValues(dst interface{}, needEmptyValue ...bool) (url.Values, error)
- func EncodeToValuesWith(dst interface{}, d rune, e rune, z bool) (url.Values, error)
- type Decoder
- func (d Decoder) Decode(dst interface{}) error
- func (d Decoder) DecodeString(dst interface{}, src string) error
- func (d Decoder) DecodeValues(dst interface{}, vs url.Values) error
- func (d *Decoder) DelimitWith(r rune) *Decoder
- func (d *Decoder) EscapeWith(r rune) *Decoder
- func (d *Decoder) IgnoreCase(ignoreCase bool)
- func (d *Decoder) IgnoreUnknownKeys(ignoreUnknown bool)
- func (d *Decoder) KeysWith(f func(string) string) *Decoder
- func (d *Decoder) MaxBytes(maxBytes int64) *Decoder
- func (d *Decoder) MaxDepth(maxDepth int) *Decoder
- func (d *Decoder) MaxSize(maxSize int) *Decoder
- func (d *Decoder) Reset(r io.Reader) *Decoder
- type Encoder
- func (e *Encoder) DelimitWith(r rune) *Encoder
- func (e Encoder) Encode(dst interface{}) error
- func (e *Encoder) EscapeWith(r rune) *Encoder
- func (e *Encoder) HexColors(h bool) *Encoder
- func (e *Encoder) KeepZeros(z bool) *Encoder
- func (e *Encoder) KeysWith(f func(string) string) *Encoder
- func (e *Encoder) OmitEmpty(o bool) *Encoder
- func (e *Encoder) Reset(w io.Writer) *Encoder
- type Error
- type Kind
- type Op
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DecodeString ¶
DecodeString decodes src into dst.
Example ¶
package main
import (
"fmt"
"github.com/ajg/form"
)
func main() {
type profile struct {
Name string `form:"name"`
Age int `form:"age"`
Tags []string `form:"tags"`
}
var p profile
if err := form.DecodeString(&p, "name=Alice&age=30&tags.0=go&tags.1=forms"); err != nil {
panic(err)
}
fmt.Printf("%s is %d; tags=%v", p.Name, p.Age, p.Tags)
}
Output: Alice is 30; tags=[go forms]
func DecodeValues ¶
DecodeValues decodes vs into dst.
func EncodeToString ¶
EncodeToString encodes dst as a form and returns it as a string.
Example ¶
package main
import (
"fmt"
"github.com/ajg/form"
)
func main() {
type profile struct {
Name string `form:"name"`
Age int `form:"age"`
}
// Keys come out sorted, so encoding is deterministic.
s, err := form.EncodeToString(&profile{Name: "Alice", Age: 30})
if err != nil {
panic(err)
}
fmt.Println(s)
}
Output: age=30&name=Alice
func EncodeToStringWith ¶ added in v1.7.0
EncodeToStringWith encodes dst as a form with delimiter d, escape e, keeping zero values if z, and returns it as a string. The delimiter and escape must differ.
func EncodeToValues ¶
EncodeToValues encodes dst as a form and returns it as Values.
Types ¶
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes data from a form (application/x-www-form-urlencoded).
Example ¶
package main
import (
"fmt"
"strings"
"github.com/ajg/form"
)
func main() {
// Decode directly from any io.Reader — e.g. an HTTP request body.
// Nested keys use dotted paths.
type request struct {
User struct {
Name string `form:"name"`
Age int `form:"age"`
} `form:"user"`
}
var req request
if err := form.NewDecoder(strings.NewReader("user.name=Bob&user.age=42")).Decode(&req); err != nil {
panic(err)
}
fmt.Printf("%+v", req)
}
Output: {User:{Name:Bob Age:42}}
func (Decoder) DecodeString ¶
DecodeString decodes src into dst.
func (Decoder) DecodeValues ¶
DecodeValues decodes vs into dst.
func (*Decoder) DelimitWith ¶
DelimitWith sets r as the delimiter used for composite keys by Decoder d and returns the latter; it is '.' by default. The delimiter must differ from the escape (validated when decoding) and should not occur unescaped within keys.
func (*Decoder) EscapeWith ¶
EscapeWith sets r as the escape used for delimiters (and to escape itself) by Decoder d and returns the latter; it is '\\' by default. The escape must differ from the delimiter (validated when decoding).
func (*Decoder) IgnoreCase ¶
IgnoreCase if set to true it will make the Decoder try to set values in the destination object even if the case does not match.
func (*Decoder) IgnoreUnknownKeys ¶
IgnoreUnknownKeys if set to true it will make the Decoder ignore values that are not found in the destination object instead of returning an error.
func (*Decoder) KeysWith ¶ added in v1.9.0
KeysWith sets f as a transformation applied to struct field names — at every nesting level — to obtain their form keys, and returns the Decoder. Fields with an explicit tag are exempt: tags always name keys verbatim. Use it to map Go naming to a wire convention, e.g. snake_case:
d.KeysWith(strcase.ToSnake) // or any func(string) string
Passing nil clears the transformation, restoring default field-name matching. f is only ever called with struct field names — never with input data — and must be deterministic, return non-empty keys, and be injective over a struct's field names, tagged ones included: unstable or colliding outputs yield unspecified (though safe) matching. Outputs should avoid the reserved implicit-index key "_" and the delimiter rune (a delimiter within a mapped name is escaped on the wire, which other consumers may not expect). A panic inside f is recovered into a *Error like any other decoding failure.
The same transformation should be set on the Encoder (see Encoder.KeysWith) for values to round-trip. Configure IgnoreCase separately if case-insensitive matching of the transformed keys is also desired.
func (*Decoder) MaxBytes ¶ added in v1.9.0
MaxBytes bounds how many bytes of input Decode will read into memory before parsing, guarding against memory exhaustion from an oversized payload. A value > 0 sets the bound; a larger input yields a KindLimit error. Values <= 0 leave input unbounded — the default, for compatibility; bound untrusted streams explicitly here or by wrapping the reader (e.g. with http.MaxBytesReader). It applies only to Decode: DecodeString and DecodeValues receive already-materialized input.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/ajg/form"
)
func main() {
// Bound how much raw input a Decoder will buffer from an untrusted
// stream; oversized input fails instead of being read into memory.
var m map[string]string
oversized := "a=" + strings.Repeat("x", 1000)
err := form.NewDecoder(strings.NewReader(oversized)).MaxBytes(32).Decode(&m)
fmt.Println(err != nil)
}
Output: true
func (*Decoder) MaxDepth ¶ added in v1.7.2
MaxDepth overrides the maximum key-path nesting depth the Decoder will parse, guarding against stack exhaustion and nested-map blow-up from a single key with many delimiters (e.g. "a.a.a.…=x"). Legitimate nesting is bounded by the destination type, so the default sits far above any real form. A value > 0 sets the limit; a value < 0 disables it (trusted input only); the zero value uses the built-in default.
func (*Decoder) MaxSize ¶ added in v1.7.2
MaxSize overrides how large a slice the Decoder will grow in response to an explicit index in the input, guarding against memory exhaustion from a small payload with a very large index (e.g. "Foo.900000000=x").
By default (the zero value) the Decoder uses a bound proportional to the number of elements actually supplied, so legitimately large slices decode while amplification is prevented; most callers never need this method. A value > 0 sets a fixed absolute cap instead (use a large value to permit large sparse slices in trusted input, or a small one to tighten the limit). A value < 0 disables the bound entirely; only do this for fully trusted input.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder provides a way to encode to a Writer.
func (*Encoder) DelimitWith ¶
DelimitWith sets r as the delimiter used for composite keys by Encoder e and returns the latter; it is '.' by default. The delimiter must differ from the escape (validated when encoding).
func (*Encoder) EscapeWith ¶
EscapeWith sets r as the escape used for delimiters (and to escape itself) by Encoder e and returns the latter; it is '\\' by default. The escape must differ from the delimiter (validated when encoding).
func (*Encoder) HexColors ¶ added in v1.9.0
HexColors makes the Encoder render the fixed-channel image/color types as bare lowercase hex strings (e.g. color.NRGBA => "ff007f80"; see color.go for the per-type formats) instead of as composite structs (C.R=255&C.G=0&…). It is false by default, preserving the existing composite wire format for current consumers. Decoding accepts both representations regardless.
func (*Encoder) KeepZeros ¶
KeepZeros sets whether Encoder e should keep zero (default) values in their literal form when encoding, and returns the former; by default zero values are not kept, but are rather encoded as the empty string.
func (*Encoder) KeysWith ¶ added in v1.9.0
KeysWith sets f as a transformation applied to struct field names — at every nesting level — to obtain their form keys, and returns the Encoder. Fields with an explicit tag are exempt: tags always name keys verbatim. Passing nil clears the transformation. f is only ever called with struct field names — never with data being encoded — and must be deterministic, return non-empty keys, and be injective over a struct's field names, tagged ones included; colliding outputs yield an unspecified (though safe) result, and outputs should avoid the reserved implicit-index key "_" and the delimiter rune. A panic inside f is recovered into a *Error. Set the same transformation on the Decoder (see Decoder.KeysWith) for values to round-trip.
type Error ¶ added in v1.8.0
type Error struct {
Op Op // the operation that failed
Kind Kind // the class of failure; empty when unclassified
Err error // the underlying cause, if any; nil when the message originates here
// contains filtered or unexported fields
}
Error is the error type returned by Decode and Encode operations for malformed input or values that cannot be represented. Callers can use errors.As to detect it and inspect Op and Kind, and errors.Unwrap (via Err) to reach an underlying cause such as an error from a TextMarshaler or TextUnmarshaler.
The text returned by the Error method is identical to that of earlier versions, so code matching on error strings is unaffected.
func NewError ¶ added in v1.9.0
NewError returns an *Error with the given operation, kind, underlying cause (which may be nil) and message. It exists so that packages built on top of form (such as form/multipart) can return errors that participate in the same errors.As taxonomy.
func NewErrorf ¶ added in v1.9.0
NewErrorf is NewError with fmt.Errorf-style message formatting. Like NewError it exists for packages built on top of form; the formatting is performed eagerly, exactly as a fmt.Sprintf at the call site would be.
type Kind ¶ added in v1.9.0
type Kind string
Kind classifies the failure that produced an Error. The zero value means the failure is unclassified — typically an error propagated from a custom TextMarshaler/TextUnmarshaler or another external source; use Unwrap (via errors.As/Is) to reach the cause.
const ( // KindSyntax reports input that is not well-formed // application/x-www-form-urlencoded data. KindSyntax Kind = "syntax" // KindParse reports a value that cannot be parsed as the destination // type (e.g. "abc" into an int, or an invalid time). KindParse Kind = "parse" // KindUnknownKey reports a key with no corresponding destination field; // see Decoder.IgnoreUnknownKeys. KindUnknownKey Kind = "unknown-key" // KindIndex reports an explicit index that is not a valid position in // the destination (malformed, negative, or beyond an array's bounds). KindIndex Kind = "index" // KindLimit reports input that exceeds a decoder resource bound; see // Decoder.MaxSize and Decoder.MaxDepth. KindLimit Kind = "limit" // KindUnsupported reports a destination or value that cannot be // represented as form data (an unsupported kind, an unsettable field, or // an invalid destination). KindUnsupported Kind = "unsupported" // KindCycle reports a self-referential value encountered while encoding. KindCycle Kind = "cycle" // KindIO reports a failure reading input or writing encoded output. KindIO Kind = "io" )
Directories
¶
| Path | Synopsis |
|---|---|
|
Package multipart decodes multipart/form-data — as submitted by HTML forms containing file inputs — into Go structs, using github.com/ajg/form to decode the value fields and mapping file parts onto struct fields by name.
|
Package multipart decodes multipart/form-data — as submitted by HTML forms containing file inputs — into Go structs, using github.com/ajg/form to decode the value fields and mapping file parts onto struct fields by name. |