forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/mitchellh/mapstructure/mapstructure.go

2649 lines
45 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
// Package mapstructure exposes functionality to convert one arbitrary
2024-02-18 10:42:21 +00:00
// Go type into another, typically to convert a map[string]interface{}
2024-02-18 10:42:21 +00:00
// into a native Go structure.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// The Go structure can be arbitrarily complex, containing slices,
2024-02-18 10:42:21 +00:00
// other structs, etc. and the decoder will properly decode nested
2024-02-18 10:42:21 +00:00
// maps and so on into the proper structures in the native Go struct.
2024-02-18 10:42:21 +00:00
// See the examples to see what the decoder is capable of.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// The simplest function to start with is Decode.
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Field Tags
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// When decoding to a struct, mapstructure will use the field name by
2024-02-18 10:42:21 +00:00
// default to perform the mapping. For example, if a struct has a field
2024-02-18 10:42:21 +00:00
// "Username" then mapstructure will look for a key in the source value
2024-02-18 10:42:21 +00:00
// of "username" (case insensitive).
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type User struct {
2024-06-14 08:41:36 +00:00
// Username string
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// You can change the behavior of mapstructure by using struct tags.
2024-02-18 10:42:21 +00:00
// The default struct tag that mapstructure looks for is "mapstructure"
2024-02-18 10:42:21 +00:00
// but you can customize it using DecoderConfig.
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Renaming Fields
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// To rename the key that mapstructure looks for, use the "mapstructure"
2024-02-18 10:42:21 +00:00
// tag and set a value directly. For example, to change the "username" example
2024-02-18 10:42:21 +00:00
// above to "user":
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type User struct {
2024-06-14 08:41:36 +00:00
// Username string `mapstructure:"user"`
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Embedded Structs and Squashing
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Embedded structs are treated as if they're another field with that name.
2024-02-18 10:42:21 +00:00
// By default, the two structs below are equivalent when decoding with
2024-02-18 10:42:21 +00:00
// mapstructure:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Person struct {
2024-06-14 08:41:36 +00:00
// Name string
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Friend struct {
2024-06-14 08:41:36 +00:00
// Person
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Friend struct {
2024-06-14 08:41:36 +00:00
// Person Person
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// This would require an input that looks like below:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// map[string]interface{}{
2024-06-14 08:41:36 +00:00
// "person": map[string]interface{}{"name": "alice"},
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If your "person" value is NOT nested, then you can append ",squash" to
2024-02-18 10:42:21 +00:00
// your tag value and mapstructure will treat it as if the embedded struct
2024-02-18 10:42:21 +00:00
// were part of the struct directly. Example:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Friend struct {
2024-06-14 08:41:36 +00:00
// Person `mapstructure:",squash"`
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Now the following input would be accepted:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// map[string]interface{}{
2024-06-14 08:41:36 +00:00
// "name": "alice",
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// When decoding from a struct to a map, the squash tag squashes the struct
2024-02-18 10:42:21 +00:00
// fields into a single map. Using the example structs from above:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// Friend{Person: Person{Name: "alice"}}
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Will be decoded into a map:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// map[string]interface{}{
2024-06-14 08:41:36 +00:00
// "name": "alice",
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// DecoderConfig has a field that changes the behavior of mapstructure
2024-02-18 10:42:21 +00:00
// to always squash embedded structs.
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Remainder Values
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If there are any unmapped keys in the source value, mapstructure by
2024-02-18 10:42:21 +00:00
// default will silently ignore them. You can error by setting ErrorUnused
2024-02-18 10:42:21 +00:00
// in DecoderConfig. If you're using Metadata you can also maintain a slice
2024-02-18 10:42:21 +00:00
// of the unused keys.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// You can also use the ",remain" suffix on your tag to collect all unused
2024-02-18 10:42:21 +00:00
// values in a map. The field with this tag MUST be a map type and should
2024-02-18 10:42:21 +00:00
// probably be a "map[string]interface{}" or "map[interface{}]interface{}".
2024-02-18 10:42:21 +00:00
// See example below:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Friend struct {
2024-06-14 08:41:36 +00:00
// Name string
2024-06-14 08:41:36 +00:00
// Other map[string]interface{} `mapstructure:",remain"`
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Given the input below, Other would be populated with the other
2024-02-18 10:42:21 +00:00
// values that weren't used (everything but "name"):
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// map[string]interface{}{
2024-06-14 08:41:36 +00:00
// "name": "bob",
2024-06-14 08:41:36 +00:00
// "address": "123 Maple St.",
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Omit Empty Values
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// When decoding from a struct to any other value, you may use the
2024-02-18 10:42:21 +00:00
// ",omitempty" suffix on your tag to omit that value if it equates to
2024-02-18 10:42:21 +00:00
// the zero value. The zero value of all types is specified in the Go
2024-02-18 10:42:21 +00:00
// specification.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// For example, the zero type of a numeric type is zero ("0"). If the struct
2024-02-18 10:42:21 +00:00
// field value is zero and a numeric type, the field is empty, and it won't
2024-02-18 10:42:21 +00:00
// be encoded into the destination type.
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Source struct {
2024-06-14 08:41:36 +00:00
// Age int `mapstructure:",omitempty"`
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Unexported fields
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Since unexported (private) struct fields cannot be set outside the package
2024-02-18 10:42:21 +00:00
// where they are defined, the decoder will simply skip them.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// For this output type definition:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Exported struct {
2024-06-14 08:41:36 +00:00
// private string // this unexported field will be skipped
2024-06-14 08:41:36 +00:00
// Public string
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Using this map as input:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// map[string]interface{}{
2024-06-14 08:41:36 +00:00
// "private": "I will be ignored",
2024-06-14 08:41:36 +00:00
// "Public": "I made it through!",
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// The following struct will be decoded:
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// type Exported struct {
2024-06-14 08:41:36 +00:00
// private: "" // field is left with an empty string (zero value)
2024-06-14 08:41:36 +00:00
// Public: "I made it through!"
2024-06-14 08:41:36 +00:00
// }
2024-02-18 10:42:21 +00:00
//
2024-06-14 08:41:36 +00:00
// # Other Configuration
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// mapstructure is highly configurable. See the DecoderConfig struct
2024-02-18 10:42:21 +00:00
// for other features and options that are supported.
2024-02-18 10:42:21 +00:00
package mapstructure
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
)
// DecodeHookFunc is the callback function that can be used for
2024-02-18 10:42:21 +00:00
// data transformations. See "DecodeHook" in the DecoderConfig
2024-02-18 10:42:21 +00:00
// struct.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// The type must be one of DecodeHookFuncType, DecodeHookFuncKind, or
2024-02-18 10:42:21 +00:00
// DecodeHookFuncValue.
2024-02-18 10:42:21 +00:00
// Values are a superset of Types (Values can return types), and Types are a
2024-02-18 10:42:21 +00:00
// superset of Kinds (Types can return Kinds) and are generally a richer thing
2024-02-18 10:42:21 +00:00
// to use, but Kinds are simpler if you only need those.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// The reason DecodeHookFunc is multi-typed is for backwards compatibility:
2024-02-18 10:42:21 +00:00
// we started with Kinds and then realized Types were the better solution,
2024-02-18 10:42:21 +00:00
// but have a promise to not break backwards compat so we now support
2024-02-18 10:42:21 +00:00
// both.
2024-02-18 10:42:21 +00:00
type DecodeHookFunc interface{}
// DecodeHookFuncType is a DecodeHookFunc which has complete information about
2024-02-18 10:42:21 +00:00
// the source and target types.
2024-02-18 10:42:21 +00:00
type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error)
// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the
2024-02-18 10:42:21 +00:00
// source and target types.
2024-02-18 10:42:21 +00:00
type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error)
// DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target
2024-02-18 10:42:21 +00:00
// values.
2024-02-18 10:42:21 +00:00
type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error)
// DecoderConfig is the configuration that is used to create a new decoder
2024-02-18 10:42:21 +00:00
// and allows customization of various aspects of decoding.
2024-02-18 10:42:21 +00:00
type DecoderConfig struct {
2024-02-18 10:42:21 +00:00
// DecodeHook, if set, will be called before any decoding and any
2024-02-18 10:42:21 +00:00
// type conversion (if WeaklyTypedInput is on). This lets you modify
2024-02-18 10:42:21 +00:00
// the values before they're set down onto the resulting struct. The
2024-02-18 10:42:21 +00:00
// DecodeHook is called for every map and value in the input. This means
2024-02-18 10:42:21 +00:00
// that if a struct has embedded fields with squash tags the decode hook
2024-02-18 10:42:21 +00:00
// is called only once with all of the input data, not once for each
2024-02-18 10:42:21 +00:00
// embedded struct.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If an error is returned, the entire decode will fail with that error.
2024-02-18 10:42:21 +00:00
DecodeHook DecodeHookFunc
// If ErrorUnused is true, then it is an error for there to exist
2024-02-18 10:42:21 +00:00
// keys in the original map that were unused in the decoding process
2024-02-18 10:42:21 +00:00
// (extra keys).
2024-02-18 10:42:21 +00:00
ErrorUnused bool
// If ErrorUnset is true, then it is an error for there to exist
2024-02-18 10:42:21 +00:00
// fields in the result that were not set in the decoding process
2024-02-18 10:42:21 +00:00
// (extra fields). This only applies to decoding to a struct. This
2024-02-18 10:42:21 +00:00
// will affect all nested structs as well.
2024-02-18 10:42:21 +00:00
ErrorUnset bool
// ZeroFields, if set to true, will zero fields before writing them.
2024-02-18 10:42:21 +00:00
// For example, a map will be emptied before decoded values are put in
2024-02-18 10:42:21 +00:00
// it. If this is false, a map will be merged.
2024-02-18 10:42:21 +00:00
ZeroFields bool
// If WeaklyTypedInput is true, the decoder will make the following
2024-02-18 10:42:21 +00:00
// "weak" conversions:
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// - bools to string (true = "1", false = "0")
2024-02-18 10:42:21 +00:00
// - numbers to string (base 10)
2024-02-18 10:42:21 +00:00
// - bools to int/uint (true = 1, false = 0)
2024-02-18 10:42:21 +00:00
// - strings to int/uint (base implied by prefix)
2024-02-18 10:42:21 +00:00
// - int to bool (true if value != 0)
2024-02-18 10:42:21 +00:00
// - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
2024-02-18 10:42:21 +00:00
// FALSE, false, False. Anything else is an error)
2024-02-18 10:42:21 +00:00
// - empty array = empty map and vice versa
2024-02-18 10:42:21 +00:00
// - negative numbers to overflowed uint values (base 10)
2024-02-18 10:42:21 +00:00
// - slice of maps to a merged map
2024-02-18 10:42:21 +00:00
// - single values are converted to slices if required. Each
2024-02-18 10:42:21 +00:00
// element is weakly decoded. For example: "4" can become []int{4}
2024-02-18 10:42:21 +00:00
// if the target type is an int slice.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
WeaklyTypedInput bool
// Squash will squash embedded structs. A squash tag may also be
2024-02-18 10:42:21 +00:00
// added to an individual struct field using a tag. For example:
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// type Parent struct {
2024-02-18 10:42:21 +00:00
// Child `mapstructure:",squash"`
2024-02-18 10:42:21 +00:00
// }
2024-02-18 10:42:21 +00:00
Squash bool
// Metadata is the struct that will contain extra metadata about
2024-02-18 10:42:21 +00:00
// the decoding. If this is nil, then no metadata will be tracked.
2024-02-18 10:42:21 +00:00
Metadata *Metadata
// Result is a pointer to the struct that will contain the decoded
2024-02-18 10:42:21 +00:00
// value.
2024-02-18 10:42:21 +00:00
Result interface{}
// The tag name that mapstructure reads for field names. This
2024-02-18 10:42:21 +00:00
// defaults to "mapstructure"
2024-02-18 10:42:21 +00:00
TagName string
// IgnoreUntaggedFields ignores all struct fields without explicit
2024-02-18 10:42:21 +00:00
// TagName, comparable to `mapstructure:"-"` as default behaviour.
2024-02-18 10:42:21 +00:00
IgnoreUntaggedFields bool
// MatchName is the function used to match the map key to the struct
2024-02-18 10:42:21 +00:00
// field name or tag. Defaults to `strings.EqualFold`. This can be used
2024-02-18 10:42:21 +00:00
// to implement case-sensitive tag values, support snake casing, etc.
2024-02-18 10:42:21 +00:00
MatchName func(mapKey, fieldName string) bool
}
// A Decoder takes a raw interface value and turns it into structured
2024-02-18 10:42:21 +00:00
// data, keeping track of rich error information along the way in case
2024-02-18 10:42:21 +00:00
// anything goes wrong. Unlike the basic top-level Decode method, you can
2024-02-18 10:42:21 +00:00
// more finely control how the Decoder behaves using the DecoderConfig
2024-02-18 10:42:21 +00:00
// structure. The top-level Decode method is just a convenience that sets
2024-02-18 10:42:21 +00:00
// up the most basic Decoder.
2024-02-18 10:42:21 +00:00
type Decoder struct {
config *DecoderConfig
}
// Metadata contains information about decoding a structure that
2024-02-18 10:42:21 +00:00
// is tedious or difficult to get otherwise.
2024-02-18 10:42:21 +00:00
type Metadata struct {
2024-02-18 10:42:21 +00:00
// Keys are the keys of the structure which were successfully decoded
2024-02-18 10:42:21 +00:00
Keys []string
// Unused is a slice of keys that were found in the raw value but
2024-02-18 10:42:21 +00:00
// weren't decoded since there was no matching field in the result interface
2024-02-18 10:42:21 +00:00
Unused []string
// Unset is a slice of field names that were found in the result interface
2024-02-18 10:42:21 +00:00
// but weren't set in the decoding process since there was no matching value
2024-02-18 10:42:21 +00:00
// in the input
2024-02-18 10:42:21 +00:00
Unset []string
}
// Decode takes an input structure and uses reflection to translate it to
2024-02-18 10:42:21 +00:00
// the output structure. output must be a pointer to a map or struct.
2024-02-18 10:42:21 +00:00
func Decode(input interface{}, output interface{}) error {
2024-02-18 10:42:21 +00:00
config := &DecoderConfig{
2024-02-18 10:42:21 +00:00
Metadata: nil,
Result: output,
2024-02-18 10:42:21 +00:00
}
decoder, err := NewDecoder(config)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return decoder.Decode(input)
2024-02-18 10:42:21 +00:00
}
// WeakDecode is the same as Decode but is shorthand to enable
2024-02-18 10:42:21 +00:00
// WeaklyTypedInput. See DecoderConfig for more info.
2024-02-18 10:42:21 +00:00
func WeakDecode(input, output interface{}) error {
2024-02-18 10:42:21 +00:00
config := &DecoderConfig{
Metadata: nil,
Result: output,
2024-02-18 10:42:21 +00:00
WeaklyTypedInput: true,
}
decoder, err := NewDecoder(config)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return decoder.Decode(input)
2024-02-18 10:42:21 +00:00
}
// DecodeMetadata is the same as Decode, but is shorthand to
2024-02-18 10:42:21 +00:00
// enable metadata collection. See DecoderConfig for more info.
2024-02-18 10:42:21 +00:00
func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error {
2024-02-18 10:42:21 +00:00
config := &DecoderConfig{
2024-02-18 10:42:21 +00:00
Metadata: metadata,
Result: output,
2024-02-18 10:42:21 +00:00
}
decoder, err := NewDecoder(config)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return decoder.Decode(input)
2024-02-18 10:42:21 +00:00
}
// WeakDecodeMetadata is the same as Decode, but is shorthand to
2024-02-18 10:42:21 +00:00
// enable both WeaklyTypedInput and metadata collection. See
2024-02-18 10:42:21 +00:00
// DecoderConfig for more info.
2024-02-18 10:42:21 +00:00
func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error {
2024-02-18 10:42:21 +00:00
config := &DecoderConfig{
Metadata: metadata,
Result: output,
2024-02-18 10:42:21 +00:00
WeaklyTypedInput: true,
}
decoder, err := NewDecoder(config)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
return decoder.Decode(input)
2024-02-18 10:42:21 +00:00
}
// NewDecoder returns a new decoder for the given configuration. Once
2024-02-18 10:42:21 +00:00
// a decoder has been returned, the same configuration must not be used
2024-02-18 10:42:21 +00:00
// again.
2024-02-18 10:42:21 +00:00
func NewDecoder(config *DecoderConfig) (*Decoder, error) {
2024-02-18 10:42:21 +00:00
val := reflect.ValueOf(config.Result)
2024-02-18 10:42:21 +00:00
if val.Kind() != reflect.Ptr {
2024-02-18 10:42:21 +00:00
return nil, errors.New("result must be a pointer")
2024-02-18 10:42:21 +00:00
}
val = val.Elem()
2024-02-18 10:42:21 +00:00
if !val.CanAddr() {
2024-02-18 10:42:21 +00:00
return nil, errors.New("result must be addressable (a pointer)")
2024-02-18 10:42:21 +00:00
}
if config.Metadata != nil {
2024-02-18 10:42:21 +00:00
if config.Metadata.Keys == nil {
2024-02-18 10:42:21 +00:00
config.Metadata.Keys = make([]string, 0)
2024-02-18 10:42:21 +00:00
}
if config.Metadata.Unused == nil {
2024-02-18 10:42:21 +00:00
config.Metadata.Unused = make([]string, 0)
2024-02-18 10:42:21 +00:00
}
if config.Metadata.Unset == nil {
2024-02-18 10:42:21 +00:00
config.Metadata.Unset = make([]string, 0)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if config.TagName == "" {
2024-02-18 10:42:21 +00:00
config.TagName = "mapstructure"
2024-02-18 10:42:21 +00:00
}
if config.MatchName == nil {
2024-02-18 10:42:21 +00:00
config.MatchName = strings.EqualFold
2024-02-18 10:42:21 +00:00
}
result := &Decoder{
2024-02-18 10:42:21 +00:00
config: config,
}
return result, nil
2024-02-18 10:42:21 +00:00
}
// Decode decodes the given raw interface to the target pointer specified
2024-02-18 10:42:21 +00:00
// by the configuration.
2024-02-18 10:42:21 +00:00
func (d *Decoder) Decode(input interface{}) error {
2024-02-18 10:42:21 +00:00
return d.decode("", input, reflect.ValueOf(d.config.Result).Elem())
2024-02-18 10:42:21 +00:00
}
// Decodes an unknown data type into a specific reflection value.
2024-02-18 10:42:21 +00:00
func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error {
2024-02-18 10:42:21 +00:00
var inputVal reflect.Value
2024-02-18 10:42:21 +00:00
if input != nil {
2024-02-18 10:42:21 +00:00
inputVal = reflect.ValueOf(input)
// We need to check here if input is a typed nil. Typed nils won't
2024-02-18 10:42:21 +00:00
// match the "input == nil" below so we check that here.
2024-02-18 10:42:21 +00:00
if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() {
2024-02-18 10:42:21 +00:00
input = nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if input == nil {
2024-02-18 10:42:21 +00:00
// If the data is nil, then we don't set anything, unless ZeroFields is set
2024-02-18 10:42:21 +00:00
// to true.
2024-02-18 10:42:21 +00:00
if d.config.ZeroFields {
2024-02-18 10:42:21 +00:00
outVal.Set(reflect.Zero(outVal.Type()))
if d.config.Metadata != nil && name != "" {
2024-02-18 10:42:21 +00:00
d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
if !inputVal.IsValid() {
2024-02-18 10:42:21 +00:00
// If the input value is invalid, then we just set the value
2024-02-18 10:42:21 +00:00
// to be the zero value.
2024-02-18 10:42:21 +00:00
outVal.Set(reflect.Zero(outVal.Type()))
2024-02-18 10:42:21 +00:00
if d.config.Metadata != nil && name != "" {
2024-02-18 10:42:21 +00:00
d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
if d.config.DecodeHook != nil {
2024-02-18 10:42:21 +00:00
// We have a DecodeHook, so let's pre-process the input.
2024-02-18 10:42:21 +00:00
var err error
2024-02-18 10:42:21 +00:00
input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("error decoding '%s': %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
var err error
2024-02-18 10:42:21 +00:00
outputKind := getKind(outVal)
2024-02-18 10:42:21 +00:00
addMetaKey := true
2024-02-18 10:42:21 +00:00
switch outputKind {
2024-02-18 10:42:21 +00:00
case reflect.Bool:
2024-02-18 10:42:21 +00:00
err = d.decodeBool(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Interface:
2024-02-18 10:42:21 +00:00
err = d.decodeBasic(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.String:
2024-02-18 10:42:21 +00:00
err = d.decodeString(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Int:
2024-02-18 10:42:21 +00:00
err = d.decodeInt(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Uint:
2024-02-18 10:42:21 +00:00
err = d.decodeUint(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Float32:
2024-02-18 10:42:21 +00:00
err = d.decodeFloat(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Struct:
2024-02-18 10:42:21 +00:00
err = d.decodeStruct(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Map:
2024-02-18 10:42:21 +00:00
err = d.decodeMap(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Ptr:
2024-02-18 10:42:21 +00:00
addMetaKey, err = d.decodePtr(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Slice:
2024-02-18 10:42:21 +00:00
err = d.decodeSlice(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Array:
2024-02-18 10:42:21 +00:00
err = d.decodeArray(name, input, outVal)
2024-02-18 10:42:21 +00:00
case reflect.Func:
2024-02-18 10:42:21 +00:00
err = d.decodeFunc(name, input, outVal)
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
// If we reached this point then we weren't able to decode it
2024-02-18 10:42:21 +00:00
return fmt.Errorf("%s: unsupported type: %s", name, outputKind)
2024-02-18 10:42:21 +00:00
}
// If we reached here, then we successfully decoded SOMETHING, so
2024-02-18 10:42:21 +00:00
// mark the key as used if we're tracking metainput.
2024-02-18 10:42:21 +00:00
if addMetaKey && d.config.Metadata != nil && name != "" {
2024-02-18 10:42:21 +00:00
d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
2024-02-18 10:42:21 +00:00
}
return err
2024-02-18 10:42:21 +00:00
}
// This decodes a basic type (bool, int, string, etc.) and sets the
2024-02-18 10:42:21 +00:00
// value to "data" of that type.
2024-02-18 10:42:21 +00:00
func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
if val.IsValid() && val.Elem().IsValid() {
2024-02-18 10:42:21 +00:00
elem := val.Elem()
// If we can't address this element, then its not writable. Instead,
2024-02-18 10:42:21 +00:00
// we make a copy of the value (which is a pointer and therefore
2024-02-18 10:42:21 +00:00
// writable), decode into that, and replace the whole value.
2024-02-18 10:42:21 +00:00
copied := false
2024-02-18 10:42:21 +00:00
if !elem.CanAddr() {
2024-02-18 10:42:21 +00:00
copied = true
// Make *T
2024-02-18 10:42:21 +00:00
copy := reflect.New(elem.Type())
// *T = elem
2024-02-18 10:42:21 +00:00
copy.Elem().Set(elem)
// Set elem so we decode into it
2024-02-18 10:42:21 +00:00
elem = copy
2024-02-18 10:42:21 +00:00
}
// Decode. If we have an error then return. We also return right
2024-02-18 10:42:21 +00:00
// away if we're not a copy because that means we decoded directly.
2024-02-18 10:42:21 +00:00
if err := d.decode(name, data, elem); err != nil || !copied {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// If we're a copy, we need to set te final result
2024-02-18 10:42:21 +00:00
val.Set(elem.Elem())
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
dataVal := reflect.ValueOf(data)
// If the input data is a pointer, and the assigned type is the dereference
2024-02-18 10:42:21 +00:00
// of that exact pointer, then indirect it so that we can assign it.
2024-02-18 10:42:21 +00:00
// Example: *string to string
2024-02-18 10:42:21 +00:00
if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() {
2024-02-18 10:42:21 +00:00
dataVal = reflect.Indirect(dataVal)
2024-02-18 10:42:21 +00:00
}
if !dataVal.IsValid() {
2024-02-18 10:42:21 +00:00
dataVal = reflect.Zero(val.Type())
2024-02-18 10:42:21 +00:00
}
dataValType := dataVal.Type()
2024-02-18 10:42:21 +00:00
if !dataValType.AssignableTo(val.Type()) {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got '%s'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataValType)
2024-02-18 10:42:21 +00:00
}
val.Set(dataVal)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataKind := getKind(dataVal)
converted := true
2024-02-18 10:42:21 +00:00
switch {
2024-02-18 10:42:21 +00:00
case dataKind == reflect.String:
2024-02-18 10:42:21 +00:00
val.SetString(dataVal.String())
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
if dataVal.Bool() {
2024-02-18 10:42:21 +00:00
val.SetString("1")
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
val.SetString("0")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Int && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Slice && d.config.WeaklyTypedInput,
2024-02-18 10:42:21 +00:00
dataKind == reflect.Array && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
dataType := dataVal.Type()
2024-02-18 10:42:21 +00:00
elemKind := dataType.Elem().Kind()
2024-02-18 10:42:21 +00:00
switch elemKind {
2024-02-18 10:42:21 +00:00
case reflect.Uint8:
2024-02-18 10:42:21 +00:00
var uints []uint8
2024-02-18 10:42:21 +00:00
if dataKind == reflect.Array {
2024-02-18 10:42:21 +00:00
uints = make([]uint8, dataVal.Len(), dataVal.Len())
2024-02-18 10:42:21 +00:00
for i := range uints {
2024-02-18 10:42:21 +00:00
uints[i] = dataVal.Index(i).Interface().(uint8)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
uints = dataVal.Interface().([]uint8)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.SetString(string(uints))
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
converted = false
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
converted = false
2024-02-18 10:42:21 +00:00
}
if !converted {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataVal.Type(), data)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataKind := getKind(dataVal)
2024-02-18 10:42:21 +00:00
dataType := dataVal.Type()
switch {
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Int:
2024-02-18 10:42:21 +00:00
val.SetInt(dataVal.Int())
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Uint:
2024-02-18 10:42:21 +00:00
val.SetInt(int64(dataVal.Uint()))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Float32:
2024-02-18 10:42:21 +00:00
val.SetInt(int64(dataVal.Float()))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
if dataVal.Bool() {
2024-02-18 10:42:21 +00:00
val.SetInt(1)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
val.SetInt(0)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataKind == reflect.String && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
str := dataVal.String()
2024-02-18 10:42:21 +00:00
if str == "" {
2024-02-18 10:42:21 +00:00
str = "0"
2024-02-18 10:42:21 +00:00
}
i, err := strconv.ParseInt(str, 0, val.Type().Bits())
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
val.SetInt(i)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot parse '%s' as int: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
2024-02-18 10:42:21 +00:00
jn := data.(json.Number)
2024-02-18 10:42:21 +00:00
i, err := jn.Int64()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"error decoding json.Number into %s: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.SetInt(i)
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataVal.Type(), data)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataKind := getKind(dataVal)
2024-02-18 10:42:21 +00:00
dataType := dataVal.Type()
switch {
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Int:
2024-02-18 10:42:21 +00:00
i := dataVal.Int()
2024-02-18 10:42:21 +00:00
if i < 0 && !d.config.WeaklyTypedInput {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot parse '%s', %d overflows uint",
2024-02-18 10:42:21 +00:00
name, i)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.SetUint(uint64(i))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Uint:
2024-02-18 10:42:21 +00:00
val.SetUint(dataVal.Uint())
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Float32:
2024-02-18 10:42:21 +00:00
f := dataVal.Float()
2024-02-18 10:42:21 +00:00
if f < 0 && !d.config.WeaklyTypedInput {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot parse '%s', %f overflows uint",
2024-02-18 10:42:21 +00:00
name, f)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.SetUint(uint64(f))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
if dataVal.Bool() {
2024-02-18 10:42:21 +00:00
val.SetUint(1)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
val.SetUint(0)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataKind == reflect.String && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
str := dataVal.String()
2024-02-18 10:42:21 +00:00
if str == "" {
2024-02-18 10:42:21 +00:00
str = "0"
2024-02-18 10:42:21 +00:00
}
i, err := strconv.ParseUint(str, 0, val.Type().Bits())
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
val.SetUint(i)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot parse '%s' as uint: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
2024-02-18 10:42:21 +00:00
jn := data.(json.Number)
2024-02-18 10:42:21 +00:00
i, err := strconv.ParseUint(string(jn), 0, 64)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"error decoding json.Number into %s: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.SetUint(i)
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataVal.Type(), data)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataKind := getKind(dataVal)
switch {
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Bool:
2024-02-18 10:42:21 +00:00
val.SetBool(dataVal.Bool())
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Int && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
val.SetBool(dataVal.Int() != 0)
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
val.SetBool(dataVal.Uint() != 0)
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
val.SetBool(dataVal.Float() != 0)
2024-02-18 10:42:21 +00:00
case dataKind == reflect.String && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
b, err := strconv.ParseBool(dataVal.String())
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
val.SetBool(b)
2024-02-18 10:42:21 +00:00
} else if dataVal.String() == "" {
2024-02-18 10:42:21 +00:00
val.SetBool(false)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot parse '%s' as bool: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataVal.Type(), data)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataKind := getKind(dataVal)
2024-02-18 10:42:21 +00:00
dataType := dataVal.Type()
switch {
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Int:
2024-02-18 10:42:21 +00:00
val.SetFloat(float64(dataVal.Int()))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Uint:
2024-02-18 10:42:21 +00:00
val.SetFloat(float64(dataVal.Uint()))
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Float32:
2024-02-18 10:42:21 +00:00
val.SetFloat(dataVal.Float())
2024-02-18 10:42:21 +00:00
case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
if dataVal.Bool() {
2024-02-18 10:42:21 +00:00
val.SetFloat(1)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
val.SetFloat(0)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataKind == reflect.String && d.config.WeaklyTypedInput:
2024-02-18 10:42:21 +00:00
str := dataVal.String()
2024-02-18 10:42:21 +00:00
if str == "" {
2024-02-18 10:42:21 +00:00
str = "0"
2024-02-18 10:42:21 +00:00
}
f, err := strconv.ParseFloat(str, val.Type().Bits())
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
val.SetFloat(f)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot parse '%s' as float: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
2024-02-18 10:42:21 +00:00
jn := data.(json.Number)
2024-02-18 10:42:21 +00:00
i, err := jn.Float64()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"error decoding json.Number into %s: %s", name, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.SetFloat(i)
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataVal.Type(), data)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
valType := val.Type()
2024-02-18 10:42:21 +00:00
valKeyType := valType.Key()
2024-02-18 10:42:21 +00:00
valElemType := valType.Elem()
// By default we overwrite keys in the current map
2024-02-18 10:42:21 +00:00
valMap := val
// If the map is nil or we're purposely zeroing fields, make a new map
2024-02-18 10:42:21 +00:00
if valMap.IsNil() || d.config.ZeroFields {
2024-02-18 10:42:21 +00:00
// Make a new map to hold our result
2024-02-18 10:42:21 +00:00
mapType := reflect.MapOf(valKeyType, valElemType)
2024-02-18 10:42:21 +00:00
valMap = reflect.MakeMap(mapType)
2024-02-18 10:42:21 +00:00
}
// Check input type and based on the input type jump to the proper func
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
switch dataVal.Kind() {
2024-02-18 10:42:21 +00:00
case reflect.Map:
2024-02-18 10:42:21 +00:00
return d.decodeMapFromMap(name, dataVal, val, valMap)
case reflect.Struct:
2024-02-18 10:42:21 +00:00
return d.decodeMapFromStruct(name, dataVal, val, valMap)
case reflect.Array, reflect.Slice:
2024-02-18 10:42:21 +00:00
if d.config.WeaklyTypedInput {
2024-02-18 10:42:21 +00:00
return d.decodeMapFromSlice(name, dataVal, val, valMap)
2024-02-18 10:42:21 +00:00
}
fallthrough
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
2024-02-18 10:42:21 +00:00
// Special case for BC reasons (covered by tests)
2024-02-18 10:42:21 +00:00
if dataVal.Len() == 0 {
2024-02-18 10:42:21 +00:00
val.Set(valMap)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
for i := 0; i < dataVal.Len(); i++ {
2024-02-18 10:42:21 +00:00
err := d.decode(
2024-02-18 10:42:21 +00:00
name+"["+strconv.Itoa(i)+"]",
2024-02-18 10:42:21 +00:00
dataVal.Index(i).Interface(), val)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
2024-02-18 10:42:21 +00:00
valType := val.Type()
2024-02-18 10:42:21 +00:00
valKeyType := valType.Key()
2024-02-18 10:42:21 +00:00
valElemType := valType.Elem()
// Accumulate errors
2024-02-18 10:42:21 +00:00
errors := make([]string, 0)
// If the input data is empty, then we just match what the input data is.
2024-02-18 10:42:21 +00:00
if dataVal.Len() == 0 {
2024-02-18 10:42:21 +00:00
if dataVal.IsNil() {
2024-02-18 10:42:21 +00:00
if !val.IsNil() {
2024-02-18 10:42:21 +00:00
val.Set(dataVal)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
// Set to empty allocated value
2024-02-18 10:42:21 +00:00
val.Set(valMap)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
for _, k := range dataVal.MapKeys() {
2024-02-18 10:42:21 +00:00
fieldName := name + "[" + k.String() + "]"
// First decode the key into the proper type
2024-02-18 10:42:21 +00:00
currentKey := reflect.Indirect(reflect.New(valKeyType))
2024-02-18 10:42:21 +00:00
if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// Next decode the data into the proper type
2024-02-18 10:42:21 +00:00
v := dataVal.MapIndex(k).Interface()
2024-02-18 10:42:21 +00:00
currentVal := reflect.Indirect(reflect.New(valElemType))
2024-02-18 10:42:21 +00:00
if err := d.decode(fieldName, v, currentVal); err != nil {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
valMap.SetMapIndex(currentKey, currentVal)
2024-02-18 10:42:21 +00:00
}
// Set the built up map to the value
2024-02-18 10:42:21 +00:00
val.Set(valMap)
// If we had errors, return those
2024-02-18 10:42:21 +00:00
if len(errors) > 0 {
2024-02-18 10:42:21 +00:00
return &Error{errors}
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
2024-02-18 10:42:21 +00:00
typ := dataVal.Type()
2024-02-18 10:42:21 +00:00
for i := 0; i < typ.NumField(); i++ {
2024-02-18 10:42:21 +00:00
// Get the StructField first since this is a cheap operation. If the
2024-02-18 10:42:21 +00:00
// field is unexported, then ignore it.
2024-02-18 10:42:21 +00:00
f := typ.Field(i)
2024-02-18 10:42:21 +00:00
if f.PkgPath != "" {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// Next get the actual value of this field and verify it is assignable
2024-02-18 10:42:21 +00:00
// to the map value.
2024-02-18 10:42:21 +00:00
v := dataVal.Field(i)
2024-02-18 10:42:21 +00:00
if !v.Type().AssignableTo(valMap.Type().Elem()) {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem())
2024-02-18 10:42:21 +00:00
}
tagValue := f.Tag.Get(d.config.TagName)
2024-02-18 10:42:21 +00:00
keyName := f.Name
if tagValue == "" && d.config.IgnoreUntaggedFields {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// If Squash is set in the config, we squash the field down.
2024-02-18 10:42:21 +00:00
squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous
v = dereferencePtrToStructIfNeeded(v, d.config.TagName)
// Determine the name of the key in the map
2024-02-18 10:42:21 +00:00
if index := strings.Index(tagValue, ","); index != -1 {
2024-02-18 10:42:21 +00:00
if tagValue[:index] == "-" {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// If "omitempty" is specified in the tag, it ignores empty values.
2024-02-18 10:42:21 +00:00
if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// If "squash" is specified in the tag, we squash the field down.
2024-02-18 10:42:21 +00:00
squash = squash || strings.Index(tagValue[index+1:], "squash") != -1
2024-02-18 10:42:21 +00:00
if squash {
2024-02-18 10:42:21 +00:00
// When squashing, the embedded type can be a pointer to a struct.
2024-02-18 10:42:21 +00:00
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
2024-02-18 10:42:21 +00:00
v = v.Elem()
2024-02-18 10:42:21 +00:00
}
// The final type must be a struct
2024-02-18 10:42:21 +00:00
if v.Kind() != reflect.Struct {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" {
2024-02-18 10:42:21 +00:00
keyName = keyNameTagValue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else if len(tagValue) > 0 {
2024-02-18 10:42:21 +00:00
if tagValue == "-" {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
keyName = tagValue
2024-02-18 10:42:21 +00:00
}
switch v.Kind() {
2024-02-18 10:42:21 +00:00
// this is an embedded struct, so handle it differently
2024-02-18 10:42:21 +00:00
case reflect.Struct:
2024-02-18 10:42:21 +00:00
x := reflect.New(v.Type())
2024-02-18 10:42:21 +00:00
x.Elem().Set(v)
vType := valMap.Type()
2024-02-18 10:42:21 +00:00
vKeyType := vType.Key()
2024-02-18 10:42:21 +00:00
vElemType := vType.Elem()
2024-02-18 10:42:21 +00:00
mType := reflect.MapOf(vKeyType, vElemType)
2024-02-18 10:42:21 +00:00
vMap := reflect.MakeMap(mType)
// Creating a pointer to a map so that other methods can completely
2024-02-18 10:42:21 +00:00
// overwrite the map if need be (looking at you decodeMapFromMap). The
2024-02-18 10:42:21 +00:00
// indirection allows the underlying map to be settable (CanSet() == true)
2024-02-18 10:42:21 +00:00
// where as reflect.MakeMap returns an unsettable map.
2024-02-18 10:42:21 +00:00
addrVal := reflect.New(vMap.Type())
2024-02-18 10:42:21 +00:00
reflect.Indirect(addrVal).Set(vMap)
err := d.decode(keyName, x.Interface(), reflect.Indirect(addrVal))
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// the underlying map may have been completely overwritten so pull
2024-02-18 10:42:21 +00:00
// it indirectly out of the enclosing value.
2024-02-18 10:42:21 +00:00
vMap = reflect.Indirect(addrVal)
if squash {
2024-02-18 10:42:21 +00:00
for _, k := range vMap.MapKeys() {
2024-02-18 10:42:21 +00:00
valMap.SetMapIndex(k, vMap.MapIndex(k))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
valMap.SetMapIndex(reflect.ValueOf(keyName), vMap)
2024-02-18 10:42:21 +00:00
}
default:
2024-02-18 10:42:21 +00:00
valMap.SetMapIndex(reflect.ValueOf(keyName), v)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if val.CanAddr() {
2024-02-18 10:42:21 +00:00
val.Set(valMap)
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) (bool, error) {
2024-02-18 10:42:21 +00:00
// If the input data is nil, then we want to just set the output
2024-02-18 10:42:21 +00:00
// pointer to be nil as well.
2024-02-18 10:42:21 +00:00
isNil := data == nil
2024-02-18 10:42:21 +00:00
if !isNil {
2024-02-18 10:42:21 +00:00
switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() {
2024-02-18 10:42:21 +00:00
case reflect.Chan,
2024-02-18 10:42:21 +00:00
reflect.Func,
2024-02-18 10:42:21 +00:00
reflect.Interface,
2024-02-18 10:42:21 +00:00
reflect.Map,
2024-02-18 10:42:21 +00:00
reflect.Ptr,
2024-02-18 10:42:21 +00:00
reflect.Slice:
2024-02-18 10:42:21 +00:00
isNil = v.IsNil()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if isNil {
2024-02-18 10:42:21 +00:00
if !val.IsNil() && val.CanSet() {
2024-02-18 10:42:21 +00:00
nilValue := reflect.New(val.Type()).Elem()
2024-02-18 10:42:21 +00:00
val.Set(nilValue)
2024-02-18 10:42:21 +00:00
}
return true, nil
2024-02-18 10:42:21 +00:00
}
// Create an element of the concrete (non pointer) type and decode
2024-02-18 10:42:21 +00:00
// into that. Then set the value of the pointer to this type.
2024-02-18 10:42:21 +00:00
valType := val.Type()
2024-02-18 10:42:21 +00:00
valElemType := valType.Elem()
2024-02-18 10:42:21 +00:00
if val.CanSet() {
2024-02-18 10:42:21 +00:00
realVal := val
2024-02-18 10:42:21 +00:00
if realVal.IsNil() || d.config.ZeroFields {
2024-02-18 10:42:21 +00:00
realVal = reflect.New(valElemType)
2024-02-18 10:42:21 +00:00
}
if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil {
2024-02-18 10:42:21 +00:00
return false, err
2024-02-18 10:42:21 +00:00
}
val.Set(realVal)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
if err := d.decode(name, data, reflect.Indirect(val)); err != nil {
2024-02-18 10:42:21 +00:00
return false, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return false, nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
// Create an element of the concrete (non pointer) type and decode
2024-02-18 10:42:21 +00:00
// into that. Then set the value of the pointer to this type.
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
if val.Type() != dataVal.Type() {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
2024-02-18 10:42:21 +00:00
name, val.Type(), dataVal.Type(), data)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
val.Set(dataVal)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataValKind := dataVal.Kind()
2024-02-18 10:42:21 +00:00
valType := val.Type()
2024-02-18 10:42:21 +00:00
valElemType := valType.Elem()
2024-02-18 10:42:21 +00:00
sliceType := reflect.SliceOf(valElemType)
// If we have a non array/slice type then we first attempt to convert.
2024-02-18 10:42:21 +00:00
if dataValKind != reflect.Array && dataValKind != reflect.Slice {
2024-02-18 10:42:21 +00:00
if d.config.WeaklyTypedInput {
2024-02-18 10:42:21 +00:00
switch {
2024-02-18 10:42:21 +00:00
// Slice and array we use the normal logic
2024-02-18 10:42:21 +00:00
case dataValKind == reflect.Slice, dataValKind == reflect.Array:
2024-02-18 10:42:21 +00:00
break
// Empty maps turn into empty slices
2024-02-18 10:42:21 +00:00
case dataValKind == reflect.Map:
2024-02-18 10:42:21 +00:00
if dataVal.Len() == 0 {
2024-02-18 10:42:21 +00:00
val.Set(reflect.MakeSlice(sliceType, 0, 0))
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Create slice of maps of other sizes
2024-02-18 10:42:21 +00:00
return d.decodeSlice(name, []interface{}{data}, val)
case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8:
2024-02-18 10:42:21 +00:00
return d.decodeSlice(name, []byte(dataVal.String()), val)
// All other types we try to convert to the slice type
2024-02-18 10:42:21 +00:00
// and "lift" it into it. i.e. a string becomes a string slice.
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
// Just re-try this function with data as a slice.
2024-02-18 10:42:21 +00:00
return d.decodeSlice(name, []interface{}{data}, val)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s': source data must be an array or slice, got %s", name, dataValKind)
2024-02-18 10:42:21 +00:00
}
// If the input value is nil, then don't allocate since empty != nil
2024-02-18 10:42:21 +00:00
if dataValKind != reflect.Array && dataVal.IsNil() {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
valSlice := val
2024-02-18 10:42:21 +00:00
if valSlice.IsNil() || d.config.ZeroFields {
2024-02-18 10:42:21 +00:00
// Make a new slice to hold our result, same size as the original data.
2024-02-18 10:42:21 +00:00
valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
2024-02-18 10:42:21 +00:00
}
// Accumulate any errors
2024-02-18 10:42:21 +00:00
errors := make([]string, 0)
for i := 0; i < dataVal.Len(); i++ {
2024-02-18 10:42:21 +00:00
currentData := dataVal.Index(i).Interface()
2024-02-18 10:42:21 +00:00
for valSlice.Len() <= i {
2024-02-18 10:42:21 +00:00
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
currentField := valSlice.Index(i)
fieldName := name + "[" + strconv.Itoa(i) + "]"
2024-02-18 10:42:21 +00:00
if err := d.decode(fieldName, currentData, currentField); err != nil {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// Finally, set the value to the slice we built up
2024-02-18 10:42:21 +00:00
val.Set(valSlice)
// If there were errors, we return those
2024-02-18 10:42:21 +00:00
if len(errors) > 0 {
2024-02-18 10:42:21 +00:00
return &Error{errors}
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
2024-02-18 10:42:21 +00:00
dataValKind := dataVal.Kind()
2024-02-18 10:42:21 +00:00
valType := val.Type()
2024-02-18 10:42:21 +00:00
valElemType := valType.Elem()
2024-02-18 10:42:21 +00:00
arrayType := reflect.ArrayOf(valType.Len(), valElemType)
valArray := val
if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields {
2024-02-18 10:42:21 +00:00
// Check input type
2024-02-18 10:42:21 +00:00
if dataValKind != reflect.Array && dataValKind != reflect.Slice {
2024-02-18 10:42:21 +00:00
if d.config.WeaklyTypedInput {
2024-02-18 10:42:21 +00:00
switch {
2024-02-18 10:42:21 +00:00
// Empty maps turn into empty arrays
2024-02-18 10:42:21 +00:00
case dataValKind == reflect.Map:
2024-02-18 10:42:21 +00:00
if dataVal.Len() == 0 {
2024-02-18 10:42:21 +00:00
val.Set(reflect.Zero(arrayType))
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// All other types we try to convert to the array type
2024-02-18 10:42:21 +00:00
// and "lift" it into it. i.e. a string becomes a string array.
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
// Just re-try this function with data as a slice.
2024-02-18 10:42:21 +00:00
return d.decodeArray(name, []interface{}{data}, val)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s': source data must be an array or slice, got %s", name, dataValKind)
}
2024-02-18 10:42:21 +00:00
if dataVal.Len() > arrayType.Len() {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len())
}
// Make a new array to hold our result, same size as the original data.
2024-02-18 10:42:21 +00:00
valArray = reflect.New(arrayType).Elem()
2024-02-18 10:42:21 +00:00
}
// Accumulate any errors
2024-02-18 10:42:21 +00:00
errors := make([]string, 0)
for i := 0; i < dataVal.Len(); i++ {
2024-02-18 10:42:21 +00:00
currentData := dataVal.Index(i).Interface()
2024-02-18 10:42:21 +00:00
currentField := valArray.Index(i)
fieldName := name + "[" + strconv.Itoa(i) + "]"
2024-02-18 10:42:21 +00:00
if err := d.decode(fieldName, currentData, currentField); err != nil {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// Finally, set the value to the array we built up
2024-02-18 10:42:21 +00:00
val.Set(valArray)
// If there were errors, we return those
2024-02-18 10:42:21 +00:00
if len(errors) > 0 {
2024-02-18 10:42:21 +00:00
return &Error{errors}
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataVal := reflect.Indirect(reflect.ValueOf(data))
// If the type of the value to write to and the data match directly,
2024-02-18 10:42:21 +00:00
// then we just set it directly instead of recursing into the structure.
2024-02-18 10:42:21 +00:00
if dataVal.Type() == val.Type() {
2024-02-18 10:42:21 +00:00
val.Set(dataVal)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
dataValKind := dataVal.Kind()
2024-02-18 10:42:21 +00:00
switch dataValKind {
2024-02-18 10:42:21 +00:00
case reflect.Map:
2024-02-18 10:42:21 +00:00
return d.decodeStructFromMap(name, dataVal, val)
case reflect.Struct:
2024-02-18 10:42:21 +00:00
// Not the most efficient way to do this but we can optimize later if
2024-02-18 10:42:21 +00:00
// we want to. To convert from struct to struct we go to map first
2024-02-18 10:42:21 +00:00
// as an intermediary.
// Make a new map to hold our result
2024-02-18 10:42:21 +00:00
mapType := reflect.TypeOf((map[string]interface{})(nil))
2024-02-18 10:42:21 +00:00
mval := reflect.MakeMap(mapType)
// Creating a pointer to a map so that other methods can completely
2024-02-18 10:42:21 +00:00
// overwrite the map if need be (looking at you decodeMapFromMap). The
2024-02-18 10:42:21 +00:00
// indirection allows the underlying map to be settable (CanSet() == true)
2024-02-18 10:42:21 +00:00
// where as reflect.MakeMap returns an unsettable map.
2024-02-18 10:42:21 +00:00
addrVal := reflect.New(mval.Type())
reflect.Indirect(addrVal).Set(mval)
2024-02-18 10:42:21 +00:00
if err := d.decodeMapFromStruct(name, dataVal, reflect.Indirect(addrVal), mval); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
result := d.decodeStructFromMap(name, reflect.Indirect(addrVal), val)
2024-02-18 10:42:21 +00:00
return result
default:
2024-02-18 10:42:21 +00:00
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error {
2024-02-18 10:42:21 +00:00
dataValType := dataVal.Type()
2024-02-18 10:42:21 +00:00
if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
2024-02-18 10:42:21 +00:00
return fmt.Errorf(
2024-02-18 10:42:21 +00:00
"'%s' needs a map with string keys, has '%s' keys",
2024-02-18 10:42:21 +00:00
name, dataValType.Key().Kind())
2024-02-18 10:42:21 +00:00
}
dataValKeys := make(map[reflect.Value]struct{})
2024-02-18 10:42:21 +00:00
dataValKeysUnused := make(map[interface{}]struct{})
2024-02-18 10:42:21 +00:00
for _, dataValKey := range dataVal.MapKeys() {
2024-02-18 10:42:21 +00:00
dataValKeys[dataValKey] = struct{}{}
2024-02-18 10:42:21 +00:00
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
2024-02-18 10:42:21 +00:00
}
targetValKeysUnused := make(map[interface{}]struct{})
2024-02-18 10:42:21 +00:00
errors := make([]string, 0)
// This slice will keep track of all the structs we'll be decoding.
2024-02-18 10:42:21 +00:00
// There can be more than one struct if there are embedded structs
2024-02-18 10:42:21 +00:00
// that are squashed.
2024-02-18 10:42:21 +00:00
structs := make([]reflect.Value, 1, 5)
2024-02-18 10:42:21 +00:00
structs[0] = val
// Compile the list of all the fields that we're going to be decoding
2024-02-18 10:42:21 +00:00
// from all the structs.
2024-02-18 10:42:21 +00:00
type field struct {
field reflect.StructField
val reflect.Value
2024-02-18 10:42:21 +00:00
}
// remainField is set to a valid field set with the "remain" tag if
2024-02-18 10:42:21 +00:00
// we are keeping track of remaining values.
2024-02-18 10:42:21 +00:00
var remainField *field
fields := []field{}
2024-02-18 10:42:21 +00:00
for len(structs) > 0 {
2024-02-18 10:42:21 +00:00
structVal := structs[0]
2024-02-18 10:42:21 +00:00
structs = structs[1:]
structType := structVal.Type()
for i := 0; i < structType.NumField(); i++ {
2024-02-18 10:42:21 +00:00
fieldType := structType.Field(i)
2024-02-18 10:42:21 +00:00
fieldVal := structVal.Field(i)
2024-02-18 10:42:21 +00:00
if fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct {
2024-02-18 10:42:21 +00:00
// Handle embedded struct pointers as embedded structs.
2024-02-18 10:42:21 +00:00
fieldVal = fieldVal.Elem()
2024-02-18 10:42:21 +00:00
}
// If "squash" is specified in the tag, we squash the field down.
2024-02-18 10:42:21 +00:00
squash := d.config.Squash && fieldVal.Kind() == reflect.Struct && fieldType.Anonymous
2024-02-18 10:42:21 +00:00
remain := false
// We always parse the tags cause we're looking for other tags too
2024-02-18 10:42:21 +00:00
tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",")
2024-02-18 10:42:21 +00:00
for _, tag := range tagParts[1:] {
2024-02-18 10:42:21 +00:00
if tag == "squash" {
2024-02-18 10:42:21 +00:00
squash = true
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
if tag == "remain" {
2024-02-18 10:42:21 +00:00
remain = true
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if squash {
2024-02-18 10:42:21 +00:00
if fieldVal.Kind() != reflect.Struct {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors,
2024-02-18 10:42:21 +00:00
fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldVal.Kind()))
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
structs = append(structs, fieldVal)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// Build our field
2024-02-18 10:42:21 +00:00
if remain {
2024-02-18 10:42:21 +00:00
remainField = &field{fieldType, fieldVal}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
// Normal struct field, store it away
2024-02-18 10:42:21 +00:00
fields = append(fields, field{fieldType, fieldVal})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// for fieldType, field := range fields {
2024-02-18 10:42:21 +00:00
for _, f := range fields {
2024-02-18 10:42:21 +00:00
field, fieldValue := f.field, f.val
2024-02-18 10:42:21 +00:00
fieldName := field.Name
tagValue := field.Tag.Get(d.config.TagName)
2024-02-18 10:42:21 +00:00
tagValue = strings.SplitN(tagValue, ",", 2)[0]
2024-02-18 10:42:21 +00:00
if tagValue != "" {
2024-02-18 10:42:21 +00:00
fieldName = tagValue
2024-02-18 10:42:21 +00:00
}
rawMapKey := reflect.ValueOf(fieldName)
2024-02-18 10:42:21 +00:00
rawMapVal := dataVal.MapIndex(rawMapKey)
2024-02-18 10:42:21 +00:00
if !rawMapVal.IsValid() {
2024-02-18 10:42:21 +00:00
// Do a slower search by iterating over each key and
2024-02-18 10:42:21 +00:00
// doing case-insensitive search.
2024-02-18 10:42:21 +00:00
for dataValKey := range dataValKeys {
2024-02-18 10:42:21 +00:00
mK, ok := dataValKey.Interface().(string)
2024-02-18 10:42:21 +00:00
if !ok {
2024-02-18 10:42:21 +00:00
// Not a string key
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
if d.config.MatchName(mK, fieldName) {
2024-02-18 10:42:21 +00:00
rawMapKey = dataValKey
2024-02-18 10:42:21 +00:00
rawMapVal = dataVal.MapIndex(dataValKey)
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if !rawMapVal.IsValid() {
2024-02-18 10:42:21 +00:00
// There was no matching key in the map for the value in
2024-02-18 10:42:21 +00:00
// the struct. Remember it for potential errors and metadata.
2024-02-18 10:42:21 +00:00
targetValKeysUnused[fieldName] = struct{}{}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if !fieldValue.IsValid() {
2024-02-18 10:42:21 +00:00
// This should never happen
2024-02-18 10:42:21 +00:00
panic("field is not valid")
2024-02-18 10:42:21 +00:00
}
// If we can't set the field, then it is unexported or something,
2024-02-18 10:42:21 +00:00
// and we just continue onwards.
2024-02-18 10:42:21 +00:00
if !fieldValue.CanSet() {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
// Delete the key we're using from the unused map so we stop tracking
2024-02-18 10:42:21 +00:00
delete(dataValKeysUnused, rawMapKey.Interface())
// If the name is empty string, then we're at the root, and we
2024-02-18 10:42:21 +00:00
// don't dot-join the fields.
2024-02-18 10:42:21 +00:00
if name != "" {
2024-02-18 10:42:21 +00:00
fieldName = name + "." + fieldName
2024-02-18 10:42:21 +00:00
}
if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// If we have a "remain"-tagged field and we have unused keys then
2024-02-18 10:42:21 +00:00
// we put the unused keys directly into the remain field.
2024-02-18 10:42:21 +00:00
if remainField != nil && len(dataValKeysUnused) > 0 {
2024-02-18 10:42:21 +00:00
// Build a map of only the unused values
2024-02-18 10:42:21 +00:00
remain := map[interface{}]interface{}{}
2024-02-18 10:42:21 +00:00
for key := range dataValKeysUnused {
2024-02-18 10:42:21 +00:00
remain[key] = dataVal.MapIndex(reflect.ValueOf(key)).Interface()
2024-02-18 10:42:21 +00:00
}
// Decode it as-if we were just decoding this map onto our map.
2024-02-18 10:42:21 +00:00
if err := d.decodeMap(name, remain, remainField.val); err != nil {
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
}
// Set the map to nil so we have none so that the next check will
2024-02-18 10:42:21 +00:00
// not error (ErrorUnused)
2024-02-18 10:42:21 +00:00
dataValKeysUnused = nil
2024-02-18 10:42:21 +00:00
}
if d.config.ErrorUnused && len(dataValKeysUnused) > 0 {
2024-02-18 10:42:21 +00:00
keys := make([]string, 0, len(dataValKeysUnused))
2024-02-18 10:42:21 +00:00
for rawKey := range dataValKeysUnused {
2024-02-18 10:42:21 +00:00
keys = append(keys, rawKey.(string))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
sort.Strings(keys)
err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", "))
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
}
if d.config.ErrorUnset && len(targetValKeysUnused) > 0 {
2024-02-18 10:42:21 +00:00
keys := make([]string, 0, len(targetValKeysUnused))
2024-02-18 10:42:21 +00:00
for rawKey := range targetValKeysUnused {
2024-02-18 10:42:21 +00:00
keys = append(keys, rawKey.(string))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
sort.Strings(keys)
err := fmt.Errorf("'%s' has unset fields: %s", name, strings.Join(keys, ", "))
2024-02-18 10:42:21 +00:00
errors = appendErrors(errors, err)
2024-02-18 10:42:21 +00:00
}
if len(errors) > 0 {
2024-02-18 10:42:21 +00:00
return &Error{errors}
2024-02-18 10:42:21 +00:00
}
// Add the unused keys to the list of unused keys if we're tracking metadata
2024-02-18 10:42:21 +00:00
if d.config.Metadata != nil {
2024-02-18 10:42:21 +00:00
for rawKey := range dataValKeysUnused {
2024-02-18 10:42:21 +00:00
key := rawKey.(string)
2024-02-18 10:42:21 +00:00
if name != "" {
2024-02-18 10:42:21 +00:00
key = name + "." + key
2024-02-18 10:42:21 +00:00
}
d.config.Metadata.Unused = append(d.config.Metadata.Unused, key)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
for rawKey := range targetValKeysUnused {
2024-02-18 10:42:21 +00:00
key := rawKey.(string)
2024-02-18 10:42:21 +00:00
if name != "" {
2024-02-18 10:42:21 +00:00
key = name + "." + key
2024-02-18 10:42:21 +00:00
}
d.config.Metadata.Unset = append(d.config.Metadata.Unset, key)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func isEmptyValue(v reflect.Value) bool {
2024-02-18 10:42:21 +00:00
switch getKind(v) {
2024-02-18 10:42:21 +00:00
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
2024-02-18 10:42:21 +00:00
return v.Len() == 0
2024-02-18 10:42:21 +00:00
case reflect.Bool:
2024-02-18 10:42:21 +00:00
return !v.Bool()
2024-02-18 10:42:21 +00:00
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
2024-02-18 10:42:21 +00:00
return v.Int() == 0
2024-02-18 10:42:21 +00:00
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
2024-02-18 10:42:21 +00:00
return v.Uint() == 0
2024-02-18 10:42:21 +00:00
case reflect.Float32, reflect.Float64:
2024-02-18 10:42:21 +00:00
return v.Float() == 0
2024-02-18 10:42:21 +00:00
case reflect.Interface, reflect.Ptr:
2024-02-18 10:42:21 +00:00
return v.IsNil()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
func getKind(val reflect.Value) reflect.Kind {
2024-02-18 10:42:21 +00:00
kind := val.Kind()
switch {
2024-02-18 10:42:21 +00:00
case kind >= reflect.Int && kind <= reflect.Int64:
2024-02-18 10:42:21 +00:00
return reflect.Int
2024-02-18 10:42:21 +00:00
case kind >= reflect.Uint && kind <= reflect.Uint64:
2024-02-18 10:42:21 +00:00
return reflect.Uint
2024-02-18 10:42:21 +00:00
case kind >= reflect.Float32 && kind <= reflect.Float64:
2024-02-18 10:42:21 +00:00
return reflect.Float32
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return kind
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, tagName string) bool {
2024-02-18 10:42:21 +00:00
for i := 0; i < typ.NumField(); i++ {
2024-02-18 10:42:21 +00:00
f := typ.Field(i)
2024-02-18 10:42:21 +00:00
if f.PkgPath == "" && !checkMapstructureTags { // check for unexported fields
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if checkMapstructureTags && f.Tag.Get(tagName) != "" { // check for mapstructure tags inside
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Value {
2024-02-18 10:42:21 +00:00
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
2024-02-18 10:42:21 +00:00
return v
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
deref := v.Elem()
2024-02-18 10:42:21 +00:00
derefT := deref.Type()
2024-02-18 10:42:21 +00:00
if isStructTypeConvertibleToMap(derefT, true, tagName) {
2024-02-18 10:42:21 +00:00
return deref
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return v
2024-02-18 10:42:21 +00:00
}