variant

package
v0.0.0-...-3b6605c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2024 License: Apache-2.0 Imports: 10 Imported by: 6

Documentation

Overview

Package variant exposes types to abstract variant data and to assign it to variables (directly or via reflection).

A typed variant is created by FromString, FromBool, FromInt, FromFloat, [FromNumberInt], [FromNumberFloat] or FromBytes.

A variant backed by a chunk of json is created by [jsonvariant.FromJson].const

A variant satisfies Assignable. That is an interface that allows assignment of the internal variant value (or representation thereof) to variables, either directly ( [Assignable.AssignTo], [Assignable.AssignToString], [Assignable.AssignToBool], [Assignable.AssignToFloat], [Assignable.AssignToInt], [Assignable.AssignToBytes]) or via reflection ([Assignable.AssignToReflectValue]).

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assign

func Assign(source any, target any) error

Assign assigns a source value to a target variable (which must be a pointer to the actual value). When the source satisfies Assignable, the [Assignable.AssignTo] is used. Otherwise, the functionality from the mapstruct library is used.

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.

func DecodeHookExec

func DecodeHookExec(
	raw DecodeHookFunc,
	from reflect.Value, to reflect.Value) (interface{}, error)

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

func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error

DecodeMetadata is the same as Decode, but is shorthand to enable metadata collection. See DecoderConfig for more info.

func WeakDecode

func WeakDecode(input, output interface{}) error

WeakDecode is the same as Decode but is shorthand to enable WeaklyTypedInput. See DecoderConfig for more info.

func WeakDecodeMetadata

func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error

WeakDecodeMetadata is the same as Decode, but is shorthand to enable both WeaklyTypedInput and metadata collection. See DecoderConfig for more info.

func WeaklyTypedHook

func WeaklyTypedHook(
	f reflect.Kind,
	t reflect.Kind,
	data interface{}) (interface{}, error)

WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to the decoder.

Note that this is significantly different from the WeaklyTypedInput option of the DecoderConfig.

Types

type Assignable

type Assignable interface {
	// AssignTo assigns the internal value to a target variable. It is important to
	// pass a pointer to the target variable, not the variable itself.
	// Returns an error when the internal value cannot be assigned to the target
	// because of a type mismatch.
	AssignTo(target any) error
	// AssignToReflectValue assigns the internal value to a reflect value.
	// Returns an error when the internal value cannot be assigned to the target
	// because of a type mismatch.
	AssignToReflectValue(targetVal *reflect.Value) error
	// AssignToString returns the internal value when it is a string.
	// Returns an error when the internal value cannot be assigned to a string
	// because of a type mismatch.
	AssignToString() (string, error)
	// AssignToBool returns the internal value when it is a bool.
	// Returns an error when the internal value cannot be assigned to a bool
	// because of a type mismatch.
	AssignToBool() (bool, error)
	// AssignToBytes returns the internal value when it is a []byte.
	// Returns an error when the internal value cannot be assigned to a byte[]
	// because of a type mismatch.
	AssignToBytes() ([]byte, error)
	// AssignToFloat returns the internal value when it is a float.
	// Returns an error when the internal value cannot be assigned to a float
	// because of a type mismatch.
	AssignToFloat() (float64, error)
	// AssignToInt returns the internal value when it is an int.
	// Returns an error when the internal value cannot be assigned to the target
	// because of a type mismatch.
	AssignToInt() (int, error)
}

Assignable represents an internal value (or representation thereof) that can be assigned to some variable. Depending on the type of the variable, conversions can be done, like transforming a map of keys and values to the proper struct format or parsing an internal buffer of json data.

func FromBool

func FromBool(value bool) Assignable

FromBool returns a new Assignable that can be assigned to a bool variable.

func FromBytes

func FromBytes(value []byte) Assignable

FromBytes returns a new Assignable that can be assigned to a []byte variable.

func FromFloat

func FromFloat(value float64) Assignable

FromFloatNumber returns a new Assignable that can be assigned to a float variable.

func FromFloatNumber

func FromFloatNumber(value float64) Assignable

FromFloatNumber returns a new Assignable that can be assigned to a float variable, or to an int variable when value does not have a fractional value.

func FromInt

func FromInt(value int64) Assignable

FromInt returns a new Assignable that can be assigned to an integer variable.

func FromIntNumber

func FromIntNumber(value int) Assignable

FromIntNumber returns a new Assignable that can be assigned to an integer or float variable.

func FromString

func FromString(value string) Assignable

FromString returns a new Assignable that can be assigned to a string variable.

Example
v := FromString("Hello")

v1, _ := v.AssignToString()
fmt.Printf("Via AssignToString: %s\n", v1)

var v2 string
v.AssignTo(&v2)
fmt.Printf("Via AssignTo: %s\n", v1)

_, err3 := v.AssignToBool()
if err3 != nil {
	fmt.Println("AssignToBool gives error")
}

var v4 bool
err4 := v.AssignTo(&v4)
if err4 != nil {
	fmt.Println("AssignTo a bool gives error")
}

var v5 any
v.AssignTo(&v5)
fmt.Printf("Via AssignTo an any: %s\n", v5)
Output:

Via AssignToString: Hello
Via AssignTo: Hello
AssignToBool gives error
AssignTo a bool gives error
Via AssignTo an any: Hello

type DecodeHookFunc

type DecodeHookFunc interface{}

DecodeHookFunc is the callback function that can be used for data transformations. See "DecodeHook" in the DecoderConfig struct.

The type must be one of DecodeHookFuncType, DecodeHookFuncKind, or DecodeHookFuncValue. Values are a superset of Types (Values can return types), and Types are a superset of Kinds (Types can return Kinds) and are generally a richer thing to use, but Kinds are simpler if you only need those.

The reason DecodeHookFunc is multi-typed is for backwards compatibility: we started with Kinds and then realized Types were the better solution, but have a promise to not break backwards compat so we now support both.

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

type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error)

DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the source and target types.

type DecodeHookFuncType

type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error)

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

type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error)

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 in case anything goes wrong. Unlike the basic top-level Decode method, you can more finely control how the Decoder behaves using the DecoderConfig structure. The top-level Decode method is just a convenience that sets up the most basic Decoder.

func NewDecoder

func NewDecoder(config *DecoderConfig) (*Decoder, error)

NewDecoder returns a new decoder for the given configuration. Once a decoder has been returned, the same configuration must not be used again.

func (*Decoder) Decode

func (d *Decoder) Decode(input interface{}) error

Decode decodes the given raw interface to the target pointer specified by the 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. The
	// DecodeHook is called for every map and value in the input. This means
	// that if a struct has embedded fields with squash tags the decode hook
	// is called only once with all of the input data, not once for each
	// embedded struct.
	//
	// If an error is returned, the entire decode will fail with that error.
	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. This
	// will affect all nested structs as well.
	ErrorUnset bool

	// ZeroFields, if set to true, will zero fields before writing them.
	// For example, a map will be emptied before decoded values are put in
	// it. If this is false, a map will be merged.
	ZeroFields bool

	// If WeaklyTypedInput is true, the decoder will make the following
	// "weak" conversions:
	//
	//   - bools to string (true = "1", false = "0")
	//   - numbers to string (base 10)
	//   - bools to int/uint (true = 1, false = 0)
	//   - strings to int/uint (base implied by prefix)
	//   - int to bool (true if value != 0)
	//   - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
	//     FALSE, false, False. Anything else is an error)
	//   - empty array = empty map and vice versa
	//   - negative numbers to overflowed uint values (base 10)
	//   - slice of maps to a merged map
	//   - single values are converted to slices if required. Each
	//     element is weakly decoded. For example: "4" can become []int{4}
	//     if the target type is an int slice.
	//
	WeaklyTypedInput bool

	// Squash will squash embedded structs.  A squash tag may also be
	// added to an individual struct field using a tag.  For example:
	//
	//  type Parent struct {
	//      Child `mapstructure:",squash"`
	//  }
	Squash bool

	// Metadata is the struct that will contain extra metadata about
	// the decoding. If this is nil, then no metadata will be tracked.
	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. This
	// defaults to "mapstructure"
	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. Defaults to `strings.EqualFold`. This can be used
	// to implement case-sensitive tag values, support snake casing, etc.
	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) Error

func (e *Error) Error() string

func (*Error) WrappedErrors

func (e *Error) WrappedErrors() []error

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL