reflectx

package module
v0.0.0-...-f196629 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2021 License: MIT Imports: 10 Imported by: 1

README

reflectx

more than reflect

Documentation

Overview

Package reflectx implements extensions to the standard reflect lib suitable for implementing marshalling and unmarshalling packages. The main Mapper type allows for Go-compatible named attribute access, including accessing embedded struct attributes and the ability to use functions and struct tags to customize field names.

Index

Constants

This section is empty.

Variables

View Source
var (
	IgnoreThisField = "-"
	//the field is skipped if empty.
	OmitEmpty = "omitempty"
	// Field is not processed further by this package.
	OmitNested = "omitnested"
	// The FieldStruct's fields will be flattened into the parent level.
	Flatten = "flatten"
	// No tag, use the original name of field
	StdMapper = NewMapper("", nil)
)
View Source
var (
	ErrNil = errors.New("nil value")
)
View Source
var (
	StructNameKey = "_struct_name"
)

Functions

func Alloc

func Alloc(t reflect.Type) (v reflect.Value)

Alloc allocate a reflect.Value which has the reflect.Type specified by t. The return value can always be set either t is a point or not.

func AllocDefault

func AllocDefault(typ reflect.Type) reflect.Value

Allocate a struct with default value, faster than SetDefault.

func AllocIndirect

func AllocIndirect(v reflect.Value) reflect.Value

IndirectAlloc returns the value that v points to. It is used before v is going to set value. If v is a nil pointer, IndirectAlloc returns a allocated Value.

func CamelCaseToUnderscore

func CamelCaseToUnderscore(str string) string

CamelCaseToUnderscore converts from camel case form to underscore separated form. Ex.: MyFunc => my_func

func CopyStruct

func CopyStruct(dst, src interface{})

CopyTo copys fields of src to dst, these fields have the same name.

func DefaultTagFunc

func DefaultTagFunc(fieldName, tag string) (string, []string)

DefaultTagFunc parses tag parts spliting by "," for the given field. Unlike StdTagFunc, the first part is not the field name. It simply returns the input fieldName.

func Deref

func Deref(t reflect.Type) reflect.Type

Deref is Indirect for reflect.Types

func FieldByIndexes

func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value

FieldByIndexes returns a value for the field given by the struct traversal for the given value.

func FieldByIndexesReadOnly

func FieldByIndexesReadOnly(v reflect.Value, indexes []int) reflect.Value

FieldByIndexesReadOnly returns a value for a particular struct traversal, but is not concerned with allocating nil pointers because the value is going to be used for reading and not setting. It returns a invalid value in case of v is a nil point.

func FieldNameToLower

func FieldNameToLower(fieldName, tag string) (string, []string)

same as StdTagFunc, but mapped fieldName to their lower case.

func FieldNameToUnderscore

func FieldNameToUnderscore(fieldName, tag string) (string, []string)

Same as StdTagFunc, but mapped fieldName to underscore. Ex.: MyFunc => my_func

func FormToStruct

func FormToStruct(form map[string][]string, ptr interface{}) error

convert map to struct

func Indirect

func Indirect(v interface{}) (reflect.Type, reflect.Value)

func IsStruct

func IsStruct(v interface{}) bool

IsStruct returns whether v or point of v is a struct.

func MustBe

func MustBe(v kinder, expected reflect.Kind)

mustBe checks a value against a kind, panicing with a reflect.ValueError if the kind isn't that which is required.

func SetDefault

func SetDefault(ptr interface{})

Set fileds of struct to default value provided by tag if they are not zero.

type Test struct {
	Field string `default:"some string"`
	Slice []int `default:"1,2,3,4,5"`
	Map map[string]int`default:"x=1,y=2,z=3"`
}

Note that the zero value of slice is nil, not []int{}.

func SetValue

func SetValue(field, v reflect.Value) error

set dst to field, auto convert types. interface{} --> base type(int, uint, float32....) float, int, uint... ->base type []interface{}, []int, []float... -> []int map[int]float... ---> map[float]float

func StdTagFunc

func StdTagFunc(fieldName, tag string) (string, []string)

StdTagFunc parses the target name and tag parts spliting by "," for the given field. e.g. Call with "foo,bar,size=64" returns ("foo", []string{"bar", "szie=64"}) Call with ",bar" returns (fieldName, []string{"bar"})

func StrToValue

func StrToValue(str string, field reflect.Value) (err error)

Set value of field by string, field must can be set.

func StructToForm

func StructToForm(obj interface{}, form map[string][]string)

convert struct to form

func UnderscoreToCamelCase

func UnderscoreToCamelCase(s string) string

UnderscoreToCamelCase converts from underscore separated form to camel case form. Ex.: my_func => MyFunc

func ValueToStr

func ValueToStr(field reflect.Value) (string, error)

Convert the value of field to string

Types

type DefaultMapper

type DefaultMapper struct {
	// contains filtered or unexported fields
}

func NewDefaultMapper

func NewDefaultMapper(tagName string, tagFunc TagFunc) *DefaultMapper

func (*DefaultMapper) AllocDefault

func (dm *DefaultMapper) AllocDefault(typ reflect.Type) reflect.Value

Allocate a struct with default value, faster than SetDefault.

func (*DefaultMapper) SetDefault

func (dm *DefaultMapper) SetDefault(ptr interface{})

type FieldInfo

type FieldInfo struct {
	Index []int
	Path  string
	IsPtr bool // is a point or not
	Type  reflect.Type
	// It is not the same as reflect.Zero, If this is a pointer, allocate a new value.
	// Zero = reflect.Zero(Deref(Type))
	Zero     reflect.Value
	Name     string
	Parts    []string          //parts of tag splite by ",", exclusive of name.
	Options  map[string]string // options parsed from Parts, as "k=v".
	Embedded bool
	Children []*FieldInfo
	Parent   *FieldInfo
}

A FieldInfo is metadata for a struct field.

func (*FieldInfo) StringsToField

func (fi *FieldInfo) StringsToField(strs []string, v reflect.Value) error

type FormMapper

type FormMapper struct {
	// contains filtered or unexported fields
}

func NewFormMapper

func NewFormMapper(tagName string, tagFunc TagFunc) FormMapper

default tagName is "form"

func (FormMapper) FormToStruct

func (fm FormMapper) FormToStruct(form map[string][]string, ptr interface{}) error

func (FormMapper) StructToForm

func (fm FormMapper) StructToForm(obj interface{}, form map[string][]string)

Convert struct to form.

type Mapper

type Mapper struct {
	// contains filtered or unexported fields
}

Mapper is a general purpose mapper of names to struct fields. A Mapper behaves like most marshallers in the standard library, obeying a field tag for name mapping but also providing a basic transform function.

func NewMapper

func NewMapper(tagName string, tagFunc TagFunc) *Mapper

NewMapper returns a new mapper using the tagName as its struct field tag. If tagName is the empty string, it is ignored. tagFunc is used to get target name and parts of tag from the field. if tagFunc is nil, StdTagFunc will be used.

func (*Mapper) FieldByPath

func (m *Mapper) FieldByPath(v reflect.Value, path string) (rv reflect.Value)

FieldByName returns a field by its mapped name as a reflect.Value. Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind. Returns zero Value if the name is not found.

func (*Mapper) FieldMap

func (m *Mapper) FieldMap(v reflect.Value) map[string]reflect.Value

FieldMap returns the mapper's mapping of field names to reflect values. Panics if v's Kind is not Struct, or v is not Indirectable to a struct kind.

func (*Mapper) FieldsByPath

func (m *Mapper) FieldsByPath(v reflect.Value, paths []string) []reflect.Value

FieldsByName returns a slice of values corresponding to the slice of names for the value. Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind. Returns zero Value for each name not found.

func (*Mapper) NameMap

func (m *Mapper) NameMap(name string) (sm StructMap, exist bool)

NameMap returns StructMap by struct name.

func (*Mapper) TraversalsByPath

func (m *Mapper) TraversalsByPath(t reflect.Type, paths []string) [][]int

TraversalsByName returns a slice of int slices which represent the struct traversals for each mapped name. Panics if t is not a struct or Indirectable to a struct. Returns empty int slice for each name not found.

func (*Mapper) TypeMap

func (m *Mapper) TypeMap(t reflect.Type) StructMap

TypeMap returns a mapping of field strings to int slices representing the traversal down the struct to reach the field.

type Reflector

type Reflector interface {
	Register(v interface{})
	Encode(v interface{}) ([]byte, error)
	Decode(b []byte) (interface{}, error)
}

json.Unmarshal or xml.Unmarshal only can decode bytes to map[]interface{}, the type of interface{} contained in map still is map[]intefface{}. Reflector can decode bytes to registed structs.

func NewReflector

func NewReflector(format, tagName string, tagFunc TagFunc) Reflector

opts can set format and tagName default format is json default tagName is "reflector" default tagFunc is StdTagfunc

type StructMap

type StructMap struct {
	Tree   *FieldInfo
	Fields []*FieldInfo          //all the fields of the tree.
	Paths  map[string]*FieldInfo // equal to Fields.
	Leaves map[string]*FieldInfo // all the leaves of the tree, not including struct type.
}

A StructMap is an index of field metadata for a struct.

func (StructMap) GetByPath

func (f StructMap) GetByPath(path string) *FieldInfo

GetByPath returns a *FieldInfo for a given string path.

func (StructMap) GetByTraversal

func (f StructMap) GetByTraversal(index []int) *FieldInfo

GetByTraversal returns a *FieldInfo for a given integer path. It is analogous to reflect.FieldByIndex, but using the cached traversal rather than re-executing the reflect machinery each time.

type TagFunc

type TagFunc func(fieldName, tag string) (name string, parts []string)

the input fieldName is equal to reflect.Field.Name() of the struct.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value represents a value that is returned from Get().

func ValueOf

func ValueOf(v interface{}) Value

ValueOf returns the Value of v.

func (Value) Bool

func (v Value) Bool() bool

Bool returns a bool format value, it returns 0.0 in case of any error.

func (Value) Default

func (v Value) Default(defaultVal interface{}) Value

Default sets defaultVal to v if v is nil.

func (Value) Float

func (v Value) Float() float64

Float returns a float format number, it returns 0.0 in case of any error.

func (Value) Int

func (v Value) Int() int

Int returns zero in case of any error.

func (Value) Int64

func (v Value) Int64() int64

Int64 returns zero in case of any error.

func (Value) Interface

func (v Value) Interface() interface{}

Interface returns v's current value as an interface{}. It is equivalent to:

var i interface{} = (v's underlying value)

func (Value) IsNil

func (v Value) IsNil() bool

IsNill returns true if v is nil.

func (Value) MustBool

func (v Value) MustBool() bool

MustBool returns the bool format value, it panics in case of any error.

func (Value) MustFloat

func (v Value) MustFloat() float64

MustFloat returns the float format number, it panics in case of any error.

func (Value) MustInt

func (v Value) MustInt() int

MustInt returns the int format number, it panics in case of any error.

func (Value) MustInt64

func (v Value) MustInt64() int64

MustInt64 returns the int64 format number, it panics in case of any error.

func (Value) MustUint

func (v Value) MustUint() uint

MustUint returns the uint format number, it panics in case of any error.

func (Value) MustUint64

func (v Value) MustUint64() uint64

MustUint64 returns the uint64 format number, it panics in case of any error.

func (Value) Plus

func (v Value) Plus(step interface{}) Value

Plus adds step to v and returns the result. The return value has the same type as v. It panics if step is not numberical. If v is nil, step will be returned.

func (Value) String

func (v Value) String() string

String returns string from v. It returns "" if v is nil.

func (Value) ToBool

func (v Value) ToBool() (bool, error)

Bool returns false in case of non-existed.

func (Value) ToFloat

func (v Value) ToFloat() (float64, error)

Float returns returns ErrNil if v is nil. It returns an error if the type of value is not numeric. Note that, if map is decode by json, evey number has float64 type. If map is decode by bson, number only has int, int64 type.

func (Value) ToInt

func (v Value) ToInt() (int, error)

ToInt returns an int number from v. It returns ErrNil if v is nil. It returns an error if the type of value is not numeric. Note that, if v is decode by json, evey number has float64 type. If v is decode by bson, number only has int, int64 type.

func (Value) ToInt64

func (v Value) ToInt64() (int64, error)

ToInt64 returns an int64 number from v. It returns ErrNil if v is nil. It returns an error if the type of value is not numeric. Note that, if v is decode by json, evey number has float64 type. If v is decode by bson, number only has int, int64 type.

func (Value) ToUint

func (v Value) ToUint() (uint, error)

ToUint returns an int number from v. It returns ErrNil if v is nil. It returns an error if the type of value is not numeric. Note that, if v is decode by json, evey number has float64 type. If v is decode by bson, number only has int, int64 type.

func (Value) ToUint64

func (v Value) ToUint64() (uint64, error)

ToUint64 returns ErrNil if v is nil. It returns an error if the type of value is not numeric. Note that, if v is decode by json, evey number has float64 type. If v is decode by bson, number only has int, int64 type.

func (Value) Uint

func (v Value) Uint() uint

Uint returns zero in case of any error.

func (Value) Uint64

func (v Value) Uint64() uint64

Uint64 returns zero in case of any error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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