Documentation
¶
Index ¶
- func Decode(input interface{}, output interface{}) error
- func DecodeHookExec(raw DecodeHookFunc, from reflect.Value, to reflect.Value) (interface{}, error)
- func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error
- func WeakDecode(input, output interface{}) error
- func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error
- func WeaklyTypedHook(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error)
- type DecodeHookFunc
- func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc
- func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc
- func RecursiveStructToMapHookFunc() DecodeHookFunc
- func StringToIPHookFunc() DecodeHookFunc
- func StringToIPNetHookFunc() DecodeHookFunc
- func StringToSliceHookFunc(sep string) DecodeHookFunc
- func StringToTimeDurationHookFunc() DecodeHookFunc
- func StringToTimeHookFunc(layout string) DecodeHookFunc
- type DecodeHookFuncKind
- type DecodeHookFuncType
- type DecodeHookFuncValue
- type Decoder
- type DecoderConfig
- type Error
- type Metadata
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Decode ¶
func Decode(input interface{}, output interface{}) error
Decode takes an input structure and uses reflection to translate it to the output structure. output must be a pointer to a map or struct.
Example ¶
type Person struct {
Name string
Age int
Emails []string
Extra map[string]string
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON where we're not quite sure of the
// struct initially.
input := map[string]interface{}{
"name": "Mitchell",
"age": 91,
"emails": []string{"one", "two", "three"},
"extra": map[string]string{
"twitter": "mitchellh",
},
}
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
Output: mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}}
Example (EmbeddedStruct) ¶
// Squashing multiple embedded structs is allowed using the squash tag.
// This is demonstrated by creating a composite struct of multiple types
// and decoding into it. In this case, a person can carry with it both
// a Family and a Location, as well as their own FirstName.
type Family struct {
LastName string
}
type Location struct {
City string
}
type Person struct {
Family `mapstructure:",squash"`
Location `mapstructure:",squash"`
FirstName string
}
input := map[string]interface{}{
"FirstName": "Mitchell",
"LastName": "Hashimoto",
"City": "San Francisco",
}
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%s %s, %s", result.FirstName, result.LastName, result.City)
Output: Mitchell Hashimoto, San Francisco
Example (Errors) ¶
type Person struct {
Name string
Age int
Emails []string
Extra map[string]string
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON where we're not quite sure of the
// struct initially.
input := map[string]interface{}{
"name": 123,
"age": "bad value",
"emails": []int{1, 2, 3},
}
var result Person
err := Decode(input, &result)
if err == nil {
panic("should have an error")
}
fmt.Println(err.Error())
Output: 5 error(s) decoding: * 'Age' expected type 'int', got unconvertible type 'string', value: 'bad value' * 'Emails[0]' expected type 'string', got unconvertible type 'int', value: '1' * 'Emails[1]' expected type 'string', got unconvertible type 'int', value: '2' * 'Emails[2]' expected type 'string', got unconvertible type 'int', value: '3' * 'Name' expected type 'string', got unconvertible type 'int', value: '123'
Example (Metadata) ¶
type Person struct {
Name string
Age int
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON where we're not quite sure of the
// struct initially.
input := map[string]interface{}{
"name": "Mitchell",
"age": 91,
"email": "foo@bar.com",
}
// For metadata, we make a more advanced DecoderConfig so we can
// more finely configure the decoder that is used. In this case, we
// just tell the decoder we want to track metadata.
var md Metadata
var result Person
config := &DecoderConfig{
Metadata: &md,
Result: &result,
}
decoder, err := NewDecoder(config)
if err != nil {
panic(err)
}
if err := decoder.Decode(input); err != nil {
panic(err)
}
fmt.Printf("Unused keys: %#v", md.Unused)
Output: Unused keys: []string{"email"}
Example (Omitempty) ¶
// Add omitempty annotation to avoid map keys for empty values
type Family struct {
LastName string
}
type Location struct {
City string
}
type Person struct {
*Family `mapstructure:",omitempty"`
*Location `mapstructure:",omitempty"`
Age int
FirstName string
}
result := &map[string]interface{}{}
input := Person{FirstName: "Somebody"}
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%+v", result)
Output: &map[Age:0 FirstName:Somebody]
Example (RemainingData) ¶
// Note that the mapstructure tags defined in the struct type
// can indicate which fields the values are mapped to.
type Person struct {
Name string
Age int
Other map[string]interface{} `mapstructure:",remain"`
}
input := map[string]interface{}{
"name": "Mitchell",
"age": 91,
"email": "mitchell@example.com",
}
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
Output: mapstructure.Person{Name:"Mitchell", Age:91, Other:map[string]interface {}{"email":"mitchell@example.com"}}
Example (Tags) ¶
// Note that the mapstructure tags defined in the struct type
// can indicate which fields the values are mapped to.
type Person struct {
Name string `mapstructure:"person_name"`
Age int `mapstructure:"person_age"`
}
input := map[string]interface{}{
"person_name": "Mitchell",
"person_age": 91,
}
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
Output: mapstructure.Person{Name:"Mitchell", Age:91}
Example (WeaklyTypedInput) ¶
type Person struct {
Name string
Age int
Emails []string
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON, generated by a weakly typed language
// such as PHP.
input := map[string]interface{}{
"name": 123, // number => string
"age": "42", // string => number
"emails": map[string]interface{}{}, // empty map => empty array
}
var result Person
config := &DecoderConfig{
WeaklyTypedInput: true,
Result: &result,
}
decoder, err := NewDecoder(config)
if err != nil {
panic(err)
}
err = decoder.Decode(input)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}}
func DecodeHookExec ¶
DecodeHookExec executes the given decode hook. This should be used since it'll naturally degrade to the older backwards compatible DecodeHookFunc that took reflect.Kind instead of reflect.Type.
func DecodeMetadata ¶
DecodeMetadata is the same as Decode, but is shorthand to enable metadata collection.
func WeakDecode ¶
func WeakDecode(input, output interface{}) error
WeakDecode is the same as Decode but is shorthand to enable WeaklyTypedInput.
func WeakDecodeMetadata ¶
WeakDecodeMetadata is the same as Decode, but is shorthand to enable both WeaklyTypedInput and metadata collection.
Types ¶
type DecodeHookFunc ¶
type DecodeHookFunc interface{}
DecodeHookFunc is the callback function that can be used for data transformations. See "DecodeHook" in the DecoderConfig struct.
func ComposeDecodeHookFunc ¶
func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc
ComposeDecodeHookFunc creates a single DecodeHookFunc that automatically composes multiple DecodeHookFuncs.
The composed funcs are called in order, with the result of the previous transformation.
func OrComposeDecodeHookFunc ¶
func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc
OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned. If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages.
func RecursiveStructToMapHookFunc ¶
func RecursiveStructToMapHookFunc() DecodeHookFunc
func StringToIPHookFunc ¶
func StringToIPHookFunc() DecodeHookFunc
StringToIPHookFunc returns a DecodeHookFunc that converts strings to net.IP
func StringToIPNetHookFunc ¶
func StringToIPNetHookFunc() DecodeHookFunc
StringToIPNetHookFunc returns a DecodeHookFunc that converts strings to net.IPNet
func StringToSliceHookFunc ¶
func StringToSliceHookFunc(sep string) DecodeHookFunc
StringToSliceHookFunc returns a DecodeHookFunc that converts string to []string by splitting on the given sep.
func StringToTimeDurationHookFunc ¶
func StringToTimeDurationHookFunc() DecodeHookFunc
StringToTimeDurationHookFunc returns a DecodeHookFunc that converts strings to time.Duration.
func StringToTimeHookFunc ¶
func StringToTimeHookFunc(layout string) DecodeHookFunc
StringToTimeHookFunc returns a DecodeHookFunc that converts strings to time.Time.
type DecodeHookFuncKind ¶
DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the source and target types.
type DecodeHookFuncType ¶
DecodeHookFuncType is a DecodeHookFunc which has complete information about the source and target types.
func TextUnmarshallerHookFunc ¶
func TextUnmarshallerHookFunc() DecodeHookFuncType
TextUnmarshallerHookFunc returns a DecodeHookFunc that applies strings to the UnmarshalText function, when the target type implements the encoding.TextUnmarshaler interface
type DecodeHookFuncValue ¶
DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target values.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
A Decoder takes a raw interface value and turns it into structured data, keeping track of rich error information along the way.
func NewDecoder ¶
func NewDecoder(config *DecoderConfig) (*Decoder, error)
NewDecoder returns a new decoder for the given configuration.
type DecoderConfig ¶
type DecoderConfig struct {
// DecodeHook, if set, will be called before any decoding and any
// type conversion (if WeaklyTypedInput is on). This lets you modify
// the values before they're set down onto the resulting struct.
DecodeHook DecodeHookFunc
// If ErrorUnused is true, then it is an error for there to exist
// keys in the original map that were unused in the decoding process
// (extra keys).
ErrorUnused bool
// If ErrorUnset is true, then it is an error for there to exist
// fields in the result that were not set in the decoding process
// (extra fields). This only applies to decoding to a struct.
ErrorUnset bool
// ZeroFields, if set to true, will zero fields before writing them.
ZeroFields bool
// If WeaklyTypedInput is true, the decoder will make "weak" conversions.
WeaklyTypedInput bool
// Squash will squash embedded structs.
Squash bool
// Metadata is the struct that will contain extra metadata about
// the decoding.
Metadata *Metadata
// Result is a pointer to the struct that will contain the decoded
// value.
Result interface{}
// The tag name that mapstructure reads for field names.
TagName string
// IgnoreUntaggedFields ignores all struct fields without explicit
// TagName, comparable to `mapstructure:"-"` as default behaviour.
IgnoreUntaggedFields bool
// MatchName is the function used to match the map key to the struct
// field name or tag.
MatchName func(mapKey, fieldName string) bool
}
DecoderConfig is the configuration that is used to create a new decoder and allows customization of various aspects of decoding.
type Error ¶
type Error struct {
Errors []string
}
Error implements the error interface and can represents multiple errors that occur in the course of a single decode.
func (*Error) WrappedErrors ¶
WrappedErrors implements the errwrap.Wrapper interface to make this return value more useful with the errwrap and go-multierror libraries.
type Metadata ¶
type Metadata struct {
// Keys are the keys of the structure which were successfully decoded
Keys []string
// Unused is a slice of keys that were found in the raw value but
// weren't decoded since there was no matching field in the result interface
Unused []string
// Unset is a slice of field names that were found in the result interface
// but weren't set in the decoding process since there was no matching value
// in the input
Unset []string
}
Metadata contains information about decoding a structure that is tedious or difficult to get otherwise.