struct2

package
v0.3.37 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2022 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package structs contains various utilities functions to work with structs.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// DefaultTagName is the default tag name for struct fields which provides
	// a more granular to tweak certain structs. Lookup the necessary functions
	// for more info.
	DefaultTagName = "structs" // struct's field default tag name
)

Functions

func Copy

func Copy(src interface{}) interface{}

Copy creates a deep copy of whatever is passed to it and returns the copy in an interface{}. The returned value will need to be asserted to the correct type.

func CopyStruct

func CopyStruct(src, dst interface{})

func CopyStruct1

func CopyStruct1(src, dst interface{})

CopyStruct ...

func DeepFields

func DeepFields(ifaceType reflect.Type) []reflect.StructField

func FillMap

func FillMap(s interface{}, out map[string]interface{})

FillMap is the same as Map. Instead of returning the output, it fills the given map.

func HasZero

func HasZero(s interface{}) bool

HasZero returns true if any field is equal to a zero value. For more info refer to Struct types HasZero() method. It panics if s's kind is not struct.

Example
// Let's define an Access struct. Note that the "Enabled" field is not
// going to be checked because we added the "structs" tag to the field.
type Access struct {
	Name         string
	LastAccessed time.Time
	Number       int
	Enabled      bool `structs:"-"`
}

// Name and Number is not initialized.
a := &Access{
	LastAccessed: time.Now(),
}
hasZeroA := HasZero(a)

// Name and Number is initialized.
b := &Access{
	Name:         "Fatih",
	LastAccessed: time.Now(),
	Number:       12345,
}
hasZeroB := HasZero(b)

fmt.Printf("%#v\n", hasZeroA)
fmt.Printf("%#v\n", hasZeroB)
Output:

true
false

func IsStruct

func IsStruct(s interface{}) bool

IsStruct returns true if the given variable is a struct or a pointer to struct.

func IsZero

func IsZero(s interface{}) bool

IsZero returns true if all fields is equal to a zero value. For more info refer to Struct types IsZero() method. It panics if s's kind is not struct.

Example
type Server struct {
	Name    string
	ID      int32
	Enabled bool
}

// Nothing is initialized
a := &Server{}
isZeroA := IsZero(a)

// Name and Enabled is initialized, but not ID
b := &Server{
	Name:    "Golang",
	Enabled: true,
}
isZeroB := IsZero(b)

fmt.Printf("%#v\n", isZeroA)
fmt.Printf("%#v\n", isZeroB)
Output:

true
false

func JsonMarshal

func JsonMarshal(value map[string]interface{}) (string, error)

The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

func JsonUnMarshal

func JsonUnMarshal(value string) (map[string]interface{}, error)

func Map

func Map(s interface{}) map[string]interface{}

Map converts the given struct to a map[string]interface{}. For more info refer to Struct types Map() method. It panics if s's kind is not struct.

Example
type Server struct {
	Name    string
	ID      int32
	Enabled bool
}

s := &Server{
	Name:    "Arslan",
	ID:      123456,
	Enabled: true,
}

m := Map(s)

fmt.Printf("%#v\n", m["Name"])
fmt.Printf("%#v\n", m["ID"])
fmt.Printf("%#v\n", m["Enabled"])
Output:

"Arslan"
123456
true
Example (OmitEmpty)
// By default field with struct types of zero values are processed too. We
// can stop processing them via "omitempty" tag option.
type Server struct {
	Name     string `structs:",omitempty"`
	ID       int32  `structs:"server_id,omitempty"`
	Location string
}

// Only add location
s := &Server{
	Location: "Tokyo",
}

m := Map(s)

// map contains only the Location field
fmt.Printf("%v\n", m)
Output:

map[Location:Tokyo]
Example (OmitNested)
// By default field with struct types are processed too. We can stop
// processing them via "omitnested" tag option.
type Server struct {
	Name string    `structs:"server_name"`
	ID   int32     `structs:"server_id"`
	Time time.Time `structs:"time,omitnested"` // do not convert to map[string]interface{}
}

const shortForm = "2006-Jan-02"
t, _ := time.Parse("2006-Jan-02", "2013-Feb-03")

s := &Server{
	Name: "Zeynep",
	ID:   789012,
	Time: t,
}

m := Map(s)

// access them by the custom tags defined above
fmt.Printf("%v\n", m["server_name"])
fmt.Printf("%v\n", m["server_id"])
fmt.Printf("%v\n", m["time"].(time.Time))
Output:

Zeynep
789012
2013-02-03 00:00:00 +0000 UTC
Example (Tags)
// Custom tags can change the map keys instead of using the fields name
type Server struct {
	Name    string `structs:"server_name"`
	ID      int32  `structs:"server_id"`
	Enabled bool   `structs:"enabled"`
}

s := &Server{
	Name: "Zeynep",
	ID:   789012,
}

m := Map(s)

// access them by the custom tags defined above
fmt.Printf("%#v\n", m["server_name"])
fmt.Printf("%#v\n", m["server_id"])
fmt.Printf("%#v\n", m["enabled"])
Output:

"Zeynep"
789012
false

func Name

func Name(s interface{}) string

Name returns the structs's type name within its package. It returns an empty string for unnamed types. It panics if s's kind is not struct.

func Names

func Names(s interface{}) []string

Names returns a slice of field names. For more info refer to Struct types Names() method. It panics if s's kind is not struct.

func Set2List

func Set2List(s []interface{}) []string

func StructCopy

func StructCopy(DstStructPtr interface{}, SrcStructPtr interface{})

func ToString

func ToString(obj interface{}) (string, error)

have all fields

func Values

func Values(s interface{}) []interface{}

Values converts the given struct to a []interface{}. For more info refer to Struct types Values() method. It panics if s's kind is not struct.

Example
type Server struct {
	Name    string
	ID      int32
	Enabled bool
}

s := &Server{
	Name:    "Fatih",
	ID:      135790,
	Enabled: false,
}

m := Values(s)

fmt.Printf("Values: %+v\n", m)
Output:

Values: [Fatih 135790 false]
Example (OmitEmpty)
// By default field with struct types of zero values are processed too. We
// can stop processing them via "omitempty" tag option.
type Server struct {
	Name     string `structs:",omitempty"`
	ID       int32  `structs:"server_id,omitempty"`
	Location string
}

// Only add location
s := &Server{
	Location: "Ankara",
}

m := Values(s)

// values contains only the Location field
fmt.Printf("Values: %+v\n", m)
Output:

Values: [Ankara]
Example (Tags)
type Location struct {
	City    string
	Country string
}

type Server struct {
	Name     string
	ID       int32
	Enabled  bool
	Location Location `structs:"-"` // values from location are not included anymore
}

s := &Server{
	Name:     "Fatih",
	ID:       135790,
	Enabled:  false,
	Location: Location{City: "Ankara", Country: "Turkey"},
}

// Let get all values from the struct s. Note that we don't include values
// from the Location field
m := Values(s)

fmt.Printf("Values: %+v\n", m)
Output:

Values: [Fatih 135790 false]

Types

type Field

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

Field represents a single struct field that encapsulates high level functions around the field.

Example
type Person struct {
	Name   string
	Number int
}

type Access struct {
	Person        Person
	HasPermission bool
	LastAccessed  time.Time
}

access := &Access{
	Person:        Person{Name: "fatih", Number: 1234567},
	LastAccessed:  time.Now(),
	HasPermission: true,
}

// Create a new Struct type
s := New(access)

// Get the Field type for "Person" field
p := s.Field("Person")

// Get the underlying "Name field" and print the value of it
name := p.Field("Name")

fmt.Printf("Value of Person.Access.Name: %+v\n", name.Value())
Output:

Value of Person.Access.Name: fatih

func Fields

func Fields(s interface{}) []*Field

Fields returns a slice of *Field. For more info refer to Struct types Fields() method. It panics if s's kind is not struct.

Example
type Access struct {
	Name         string
	LastAccessed time.Time
	Number       int
}

s := &Access{
	Name:         "Fatih",
	LastAccessed: time.Now(),
	Number:       1234567,
}

fields := Fields(s)

for i, field := range fields {
	fmt.Printf("[%d] %+v\n", i, field.Name())
}
Output:

[0] Name
[1] LastAccessed
[2] Number
Example (Nested)
type Person struct {
	Name   string
	Number int
}

type Access struct {
	Person        Person
	HasPermission bool
	LastAccessed  time.Time
}

s := &Access{
	Person:        Person{Name: "fatih", Number: 1234567},
	LastAccessed:  time.Now(),
	HasPermission: true,
}

// Let's get all fields from the struct s.
fields := Fields(s)

for _, field := range fields {
	if field.Name() == "Person" {
		fmt.Printf("Access.Person.Name: %+v\n", field.Field("Name").Value())
	}
}
Output:

Access.Person.Name: fatih

func (*Field) Field

func (f *Field) Field(name string) *Field

Field returns the field from a nested struct. It panics if the nested struct is not exported or if the field was not found.

func (*Field) FieldOk

func (f *Field) FieldOk(name string) (*Field, bool)

FieldOk returns the field from a nested struct. The boolean returns whether the field was found (true) or not (false).

func (*Field) Fields

func (f *Field) Fields() []*Field

Fields returns a slice of Fields. This is particular handy to get the fields of a nested struct . A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field *http.Request `structs:"-"`

It panics if field is not exported or if field's kind is not struct

func (*Field) IsEmbedded

func (f *Field) IsEmbedded() bool

IsEmbedded returns true if the given field is an anonymous field (embedded)

func (*Field) IsExported

func (f *Field) IsExported() bool

IsExported returns true if the given field is exported.

func (*Field) IsZero

func (f *Field) IsZero() bool

IsZero returns true if the given field is not initialized (has a zero value). It panics if the field is not exported.

func (*Field) Kind

func (f *Field) Kind() reflect.Kind

Kind returns the fields kind, such as "string", "map", "bool", etc ..

func (*Field) Name

func (f *Field) Name() string

Name returns the name of the given field

func (*Field) Set

func (f *Field) Set(val interface{}) error

Set sets the field to given value v. It returns an error if the field is not settable (not addressable or not exported) or if the given value's type doesn't match the fields type.

func (*Field) Tag

func (f *Field) Tag(key string) string

Tag returns the value associated with key in the tag string. If there is no such key in the tag, Tag returns the empty string.

func (*Field) Value

func (f *Field) Value() interface{}

Value returns the underlying value of the field. It panics if the field is not exported.

func (*Field) Zero

func (f *Field) Zero() error

Zero sets the field to its zero value. It returns an error if the field is not settable (not addressable or not exported).

type Interface

type Interface interface {
	DeepCopy() interface{}
}

Interface for delegating copy process to type

type Struct

type Struct struct {
	TagName string
	// contains filtered or unexported fields
}

Struct encapsulates a struct type to provide several high level functions around the struct.

func New

func New(s interface{}) *Struct

New returns a new *Struct with the struct s. It panics if the s's kind is not struct.

Example
type Server struct {
	Name    string
	ID      int32
	Enabled bool
}

server := &Server{
	Name:    "Arslan",
	ID:      123456,
	Enabled: true,
}

s := New(server)

fmt.Printf("Name        : %v\n", s.Name())
fmt.Printf("Values      : %v\n", s.Values())
fmt.Printf("Value of ID : %v\n", s.Field("ID").Value())
Output:

Name        : Server
Values      : [Arslan 123456 true]
Value of ID : 123456

func (*Struct) Field

func (s *Struct) Field(name string) *Field

Field returns a new Field struct that provides several high level functions around a single struct field entity. It panics if the field is not found.

func (*Struct) FieldOk

func (s *Struct) FieldOk(name string) (*Field, bool)

FieldOk returns a new Field struct that provides several high level functions around a single struct field entity. The boolean returns true if the field was found.

func (*Struct) Fields

func (s *Struct) Fields() []*Field

Fields returns a slice of Fields. A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

It panics if s's kind is not struct.

func (*Struct) FillMap

func (s *Struct) FillMap(out map[string]interface{})

FillMap is the same as Map. Instead of returning the output, it fills the given map.

func (*Struct) HasZero

func (s *Struct) HasZero() bool

HasZero returns true if a field in a struct is not initialized (zero value). A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

A value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Field is not processed further by this package.
Field time.Time     `structs:"myName,omitnested"`
Field *http.Request `structs:",omitnested"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected. It panics if s's kind is not struct.

func (*Struct) IsZero

func (s *Struct) IsZero() bool

IsZero returns true if all fields in a struct is a zero value (not initialized) A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

A value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Field is not processed further by this package.
Field time.Time     `structs:"myName,omitnested"`
Field *http.Request `structs:",omitnested"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected. It panics if s's kind is not struct.

func (*Struct) Map

func (s *Struct) Map() map[string]interface{}

Map converts the given struct to a map[string]interface{}, where the keys of the map are the field names and the values of the map the associated values of the fields. The default key string is the struct field name but can be changed in the struct field's tag value. The "structs" key in the struct's field tag value is the key name. Example:

// Field appears in map as key "myName".
Name string `structs:"myName"`

A tag value with the content of "-" ignores that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

A tag value with the content of "string" uses the stringer to get the value. Example:

// The value will be output of Animal's String() func.
// Map will panic if Animal does not implement String().
Field *Animal `structs:"field,string"`

A tag value with the option of "flatten" used in a struct field is to flatten its fields in the output map. Example:

// The FieldStruct's fields will be flattened into the output map.
FieldStruct time.Time `structs:",flatten"`

A tag value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Field is not processed further by this package.
Field time.Time     `structs:"myName,omitnested"`
Field *http.Request `structs:",omitnested"`

A tag value with the option of "omitempty" ignores that particular field if the field value is empty. Example:

// Field appears in map as key "myName", but the field is
// skipped if empty.
Field string `structs:"myName,omitempty"`

// Field appears in map as key "Field" (the default), but
// the field is skipped if empty.
Field string `structs:",omitempty"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected.

func (*Struct) Name

func (s *Struct) Name() string

Name returns the structs's type name within its package. For more info refer to Name() function.

func (*Struct) Names

func (s *Struct) Names() []string

Names returns a slice of field names. A struct tag with the content of "-" ignores the checking of that particular field. Example:

// Field is ignored by this package.
Field bool `structs:"-"`

It panics if s's kind is not struct.

func (*Struct) Values

func (s *Struct) Values() []interface{}

Values converts the given s struct's field values to a []interface{}. A struct tag with the content of "-" ignores the that particular field. Example:

// Field is ignored by this package.
Field int `structs:"-"`

A value with the option of "omitnested" stops iterating further if the type is a struct. Example:

// Fields is not processed further by this package.
Field time.Time     `structs:",omitnested"`
Field *http.Request `structs:",omitnested"`

A tag value with the option of "omitempty" ignores that particular field and is not added to the values if the field value is empty. Example:

// Field is skipped if empty
Field string `structs:",omitempty"`

Note that only exported fields of a struct can be accessed, non exported fields will be neglected.

type Tag

type Tag struct {
	// Key is the tag key, such as json, xml, etc..
	// i.e: `json:"foo,omitempty". Here key is: "json"
	Key string

	// Name is a part of the value
	// i.e: `json:"foo,omitempty". Here name is: "foo"
	Name string

	// Options is a part of the value. It contains a slice of tag options i.e:
	// `json:"foo,omitempty". Here options is: ["omitempty"]
	Options []string
}

Tag defines a single struct's string literal tag

func (*Tag) GoString

func (t *Tag) GoString() string

GoString implements the fmt.GoStringer interface

func (*Tag) HasOption

func (t *Tag) HasOption(opt string) bool

HasOption returns true if the given option is available in options

func (*Tag) String

func (t *Tag) String() string

String reassembles the tag into a valid tag field representation

func (*Tag) Value

func (t *Tag) Value() string

Value returns the raw value of the tag, i.e. if the tag is `json:"foo,omitempty", the Value is "foo,omitempty"

type Tags

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

Tags represent a set of tags from a single struct field

func Parse

func Parse(tag string) (*Tags, error)

Parse parses a single struct field tag and returns the set of tags.

func (*Tags) AddOptions

func (t *Tags) AddOptions(key string, options ...string)

AddOptions adds the given option for the given key. If the option already exists it doesn't add it again.

func (*Tags) Delete

func (t *Tags) Delete(keys ...string)

Delete deletes the tag for the given keys

func (*Tags) DeleteOptions

func (t *Tags) DeleteOptions(key string, options ...string)

DeleteOptions deletes the given options for the given key

func (*Tags) Get

func (t *Tags) Get(key string) (*Tag, error)

Get returns the tag associated with the given key. If the key is present in the tag the value (which may be empty) is returned. Otherwise the returned value will be the empty string. The ok return value reports whether the tag exists or not (which the return value is nil).

func (*Tags) Keys

func (t *Tags) Keys() []string

Tags returns a slice of tags. The order is the original tag order unless it was changed.

func (*Tags) Len

func (t *Tags) Len() int

func (*Tags) Less

func (t *Tags) Less(i int, j int) bool

func (*Tags) Set

func (t *Tags) Set(tag *Tag) error

Set sets the given tag. If the tag key already exists it'll override it

func (*Tags) String

func (t *Tags) String() string

String reassembles the tags into a valid literal tag field representation

func (*Tags) Swap

func (t *Tags) Swap(i int, j int)

func (*Tags) Tags

func (t *Tags) Tags() []*Tag

Tags returns a slice of tags. The order is the original tag order unless it was changed.

Jump to

Keyboard shortcuts

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