Documentation
¶
Overview ¶
Package rawconv implements conversions to and from raw string representations of any (custom) data type in Go.
Basic conversions ¶
Out of the box, this package supports all logical base types and some common types:
- string, rune
- bool
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64
- float32, float64
- complex64, complex128
- array, slice
- map
- time.Duration
- url.URL
- encoding.TextUnmarshaler, encoding.TextMarshaler
Array, slice and map conversions ¶
Conversions to array, slice or map are done by splitting the raw string. The separator can be set via the Options type and defaults to DefaultItemsSeparator. For maps there is also a separator for the key-value pairs, which defaults to DefaultKeyValueSeparator.
Values within the array, slice, or map are unmarshaled using the called Unmarshaler. This is also done for keys of maps.
> Nested arrays, slices and maps are not supported.
Structs ¶
This package does not contain any logic for traversing struct types, because the implementation would really depend on the use case. However, it is possible to incorporate this package in your own struct unmarshaling logic.
Custom types ¶
Custom types are supported in two ways; by implementing the encoding.TextUnmarshaler and/or encoding.TextMarshaler interfaces, or by registering a MarshalFunc with RegisterMarshalFunc and/or an UnmarshalFunc with RegisterUnmarshalFunc.
If you do not wish to globally expose your MarshalFunc or UnmarshalFunc implementations, it is possible to register them to a new Marshaler and/or Unmarshaler and use those instances in your application instead.
Index ¶
- Constants
- func RegisterMarshalFunc(typ reflect.Type, fn MarshalFunc)
- func RegisterUnmarshalFunc(typ reflect.Type, fn UnmarshalFunc)
- func Unmarshal(val Value, v any) error
- type MarshalFunc
- type Marshaler
- type Options
- type UnmarshalFunc
- type Unmarshaler
- type UnsupportedTypeError
- type Value
- func Marshal(v any) (Value, error)
- func ValueFromBool(v bool) Value
- func ValueFromComplex128(v complex128) Value
- func ValueFromComplex64(v complex64) Value
- func ValueFromFloat32(v float32) Value
- func ValueFromFloat64(v float64) Value
- func ValueFromInt(v int) Value
- func ValueFromInt16(v int16) Value
- func ValueFromInt32(v int32) Value
- func ValueFromInt64(v int64) Value
- func ValueFromInt8(v int8) Value
- func ValueFromUint(v uint) Value
- func ValueFromUint16(v uint16) Value
- func ValueFromUint32(v uint32) Value
- func ValueFromUint64(v uint64) Value
- func ValueFromUint8(v uint8) Value
- func (v Value) Bool() (bool, error)
- func (v Value) BoolVar(p *bool) (err error)
- func (v Value) Bytes() []byte
- func (v Value) BytesVar(p *[]byte)
- func (v Value) Complex128() (complex128, error)
- func (v Value) Complex128Var(p *complex128) (err error)
- func (v Value) Complex64() (complex64, error)
- func (v Value) Complex64Var(p *complex64) (err error)
- func (v Value) Duration() (time.Duration, error)
- func (v Value) DurationVar(p *time.Duration) (err error)
- func (v Value) Float32() (float32, error)
- func (v Value) Float32Var(p *float32) (err error)
- func (v Value) Float64() (float64, error)
- func (v Value) Float64Var(p *float64) (err error)
- func (v Value) GoString() string
- func (v Value) Int() (int, error)
- func (v Value) Int16() (int16, error)
- func (v Value) Int16Var(p *int16) (err error)
- func (v Value) Int32() (int32, error)
- func (v Value) Int32Var(p *int32) (err error)
- func (v Value) Int64() (int64, error)
- func (v Value) Int64Var(p *int64) (err error)
- func (v Value) Int8() (int8, error)
- func (v Value) Int8Var(p *int8) (err error)
- func (v Value) IntVar(p *int) (err error)
- func (v Value) IsEmpty() bool
- func (v Value) Rune() rune
- func (v Value) RuneVar(p *rune)
- func (v Value) String() string
- func (v Value) StringVar(p *string)
- func (v Value) Uint() (uint, error)
- func (v Value) Uint16() (uint16, error)
- func (v Value) Uint16Var(p *uint16) (err error)
- func (v Value) Uint32() (uint32, error)
- func (v Value) Uint32Var(p *uint32) (err error)
- func (v Value) Uint64() (uint64, error)
- func (v Value) Uint64Var(p *uint64) (err error)
- func (v Value) Uint8() (uint8, error)
- func (v Value) Uint8Var(p *uint8) (err error)
- func (v Value) UintVar(p *uint) (err error)
- func (v Value) Url() (*url.URL, error)
- func (v Value) UrlVar(p *url.URL) error
Examples ¶
Constants ¶
const ( ErrPointerExpected errors.Msg = "expected a non-nil pointer to a value" ErrUnmarshalNested errors.Msg = "cannot unmarshal nested array/slice/map" ErrUnableToSet errors.Msg = "unable to set value" ErrUnableToAddr errors.Msg = "unable to addr value" ErrRuneTooManyChars errors.Msg = "too many characters" ErrArrayTooManyValues errors.Msg = "too many values" ErrMapInvalidFormat errors.Msg = "invalid map format" ErrUnmarshalFuncExec errors.Msg = "error while executing UnmarshalFunc" )
const ( ErrParseFailure errors.Msg = "failed to parse" ErrValidationFailure errors.Msg = "failed to validate" )
const ( DefaultItemsSeparator = "," DefaultKeyValueSeparator = "=" )
const ErrMarshalNested errors.Msg = "cannot marshal nested array/slice/map"
Variables ¶
This section is empty.
Functions ¶
func RegisterMarshalFunc ¶
func RegisterMarshalFunc(typ reflect.Type, fn MarshalFunc)
RegisterMarshalFunc registers the MarshalFunc for typ, making it globally available for Marshal, MarshalValue, MarshalReflect and any Marshaler.
func RegisterUnmarshalFunc ¶
func RegisterUnmarshalFunc(typ reflect.Type, fn UnmarshalFunc)
RegisterUnmarshalFunc registers the UnmarshalFunc for typ, making it globally available for Unmarshal and any Unmarshaler.
func Unmarshal ¶
Unmarshal parses Value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an ErrPointerExpected error. If v is not a supported type an UnsupportedTypeError is returned. By default, the following types are supported:
- string
- bool
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64
- float32, float64
- complex64, complex128
- array, slice
- map
- time.Duration
- url.URL
- encoding.TextUnmarshaler
Use RegisterUnmarshalFunc to add additional (custom) types.
Example ¶
Below example demonstrates how to unmarshal a raw string into a time.Duration type using Unmarshal.
var duration time.Duration if err := Unmarshal("1h2m3s", &duration); err != nil { panic(err) } fmt.Println(duration)
Output: 1h2m3s
Types ¶
type MarshalFunc ¶
func GetMarshalFunc ¶
func GetMarshalFunc(typ reflect.Type) MarshalFunc
GetMarshalFunc returns the globally registered MarshalFunc for reflect.Type typ or nil if there is none registered with RegisterMarshalFunc.
type Marshaler ¶
type Marshaler struct { Options // contains filtered or unexported fields }
Marshaler is a type which can marshal any reflect.Value to its raw string representation as long as it's registered with Register. It wil always fallback to the global Marshaler when a type is not registered.
Example ¶
var m Marshaler target, _ := url.ParseRequestURI("https://example.com") val, err := m.Marshal(reflect.ValueOf(target)) if err != nil { panic(err) } fmt.Println(val.String())
Output: https://example.com
func (*Marshaler) Func ¶
func (m *Marshaler) Func(typ reflect.Type) MarshalFunc
Func returns the (globally) registered MarshalFunc for reflect.Type typ or nil if there is none registered with Register or RegisterMarshalFunc.
type UnmarshalFunc ¶
UnmarshalFunc is a function which can unmarshal a Value to any type. Argument dest is always a pointer to the value to unmarshal to.
func GetUnmarshalFunc ¶
func GetUnmarshalFunc(typ reflect.Type) UnmarshalFunc
GetUnmarshalFunc returns the globally registered UnmarshalFunc for reflect.Type typ or nil if there is none registered with RegisterUnmarshalFunc.
func (UnmarshalFunc) Exec ¶
func (fn UnmarshalFunc) Exec(v Value, dest reflect.Value) error
Exec executes the UnmarshalFunc by taking the address of dest, and passing it as an interface to UnmarshalFunc. It will return an error when the address of reflect.Value dest cannot be taken, or when it is unable to set. Any error returned by UnmarshalFunc is wrapped with ErrParseFailure.
type Unmarshaler ¶
type Unmarshaler struct { Options // contains filtered or unexported fields }
Unmarshaler is a type which can unmarshal a Value to any type that's registered with Register. It wil always fallback to the global Unmarshaler when a type is not registered.
Example ¶
var u Unmarshaler var target *url.URL if err := u.Unmarshal("https://example.com", reflect.ValueOf(&target)); err != nil { panic(err) } fmt.Println(target.String())
Output: https://example.com
func (*Unmarshaler) Func ¶
func (u *Unmarshaler) Func(typ reflect.Type) UnmarshalFunc
Func returns the (globally) registered UnmarshalFunc for reflect.Type typ or nil if there is none registered with Register or RegisterUnmarshalFunc.
func (*Unmarshaler) Register ¶
func (u *Unmarshaler) Register(typ reflect.Type, fn UnmarshalFunc) *Unmarshaler
Register the UnmarshalFunc for typ but only for this Unmarshaler.
Example ¶
type myType struct { something string } var u Unmarshaler u.Register(reflect.TypeOf(myType{}), func(val Value, dest any) error { mt := dest.(*myType) mt.something = val.String() return nil }) var target myType if err := u.Unmarshal("some value", reflect.ValueOf(&target)); err != nil { panic(err) } spew.Dump(target)
Output: (rawconv.myType) { something: (string) (len=10) "some value" }
func (*Unmarshaler) Unmarshal ¶
func (u *Unmarshaler) Unmarshal(val Value, v reflect.Value) error
Unmarshal tries to unmarshal Value to a supported type which matches the type of v, and sets the parsed value to it. See Unmarshal for additional details.
Example ¶
var u Unmarshaler u.ItemsSeparator = ";" var list []string if err := u.Unmarshal("foo;bar", reflect.ValueOf(&list)); err != nil { panic(err) } fmt.Println(list)
Output: [foo bar]
type UnsupportedTypeError ¶
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
func (*UnsupportedTypeError) Is ¶
func (e *UnsupportedTypeError) Is(err error) bool
type Value ¶
type Value string
Value is a textual representation of a raw value which is able to cast itself to any of the supported types using its corresponding method.
boolVal, err := rawconv.Value("true").Bool()
func Marshal ¶
Marshal formats the value pointed to by v to a raw string Value. If v is not a supported type an UnsupportedTypeError is returned. By default, the following types are supported:
- encoding.TextMarshaler
- string
- bool
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64
- float32, float64
- complex64, complex128
- array, slice
- map
- time.Duration
- url.URL
Use RegisterMarshalFunc to add additional (custom) types.
Example ¶
duration := time.Hour + (time.Minute * 2) + (time.Second * 3) val, err := Marshal(duration) if err != nil { panic(err) } fmt.Println(val.String())
Output: 1h2m3s
func ValueFromBool ¶ added in v0.5.0
ValueFromBool encodes v to a Value using strconv.FormatBool.
func ValueFromComplex128 ¶ added in v0.5.0
func ValueFromComplex128(v complex128) Value
ValueFromComplex128 encodes v to a Value using strconv.FormatComplex.
func ValueFromComplex64 ¶ added in v0.5.0
ValueFromComplex64 encodes v to a Value using strconv.FormatComplex.
func ValueFromFloat32 ¶ added in v0.5.0
ValueFromFloat32 encodes v to a Value using strconv.FormatFloat.
func ValueFromFloat64 ¶ added in v0.5.0
ValueFromFloat64 encodes v to a Value using strconv.FormatFloat.
func ValueFromInt ¶ added in v0.5.0
ValueFromInt encodes v to a Value using strconv.FormatInt.
func ValueFromInt16 ¶ added in v0.5.0
ValueFromInt16 encodes v to a Value using strconv.FormatInt.
func ValueFromInt32 ¶ added in v0.5.0
ValueFromInt32 encodes v to a Value using strconv.FormatInt.
func ValueFromInt64 ¶ added in v0.5.0
ValueFromInt64 encodes v to a Value using strconv.FormatInt.
func ValueFromInt8 ¶ added in v0.5.0
ValueFromInt8 encodes v to a Value using strconv.FormatInt.
func ValueFromUint ¶ added in v0.5.0
ValueFromUint encodes v to a Value using strconv.FormatUint.
func ValueFromUint16 ¶ added in v0.5.0
ValueFromUint16 encodes v to a Value using strconv.FormatUint.
func ValueFromUint32 ¶ added in v0.5.0
ValueFromUint32 encodes v to a Value using strconv.FormatUint.
func ValueFromUint64 ¶ added in v0.5.0
ValueFromUint64 encodes v to a Value using strconv.FormatUint.
func ValueFromUint8 ¶ added in v0.5.0
ValueFromUint8 encodes v to a Value using strconv.FormatUint.
func (Value) Bool ¶
Bool tries to parse Value as a bool using strconv.ParseBool. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.
func (Value) Complex128 ¶
func (v Value) Complex128() (complex128, error)
Complex128 tries to parse Value as a complex128 using strconv.ParseComplex.
func (Value) Complex128Var ¶
func (v Value) Complex128Var(p *complex128) (err error)
Complex128Var sets the value p points to using Complex128.
func (Value) Complex64Var ¶
Complex64Var sets the value p points to using Complex64.
func (Value) DurationVar ¶
DurationVar sets the value p points to using Duration.
func (Value) Float32Var ¶
Float32Var sets the value p points to using Float32.
func (Value) Float64Var ¶
Float64Var sets the value p points to using Float64.
func (Value) RuneVar ¶ added in v0.5.2
RuneVar sets the value p points to, to the first rune of Value.