Documentation ¶
Overview ¶
Package model provides robust and easy-to-use model mapper and utility methods for Go. These typical methods increase productivity and make Go development more fun :)
Index ¶
- Constants
- Variables
- func AddConversion(in interface{}, out interface{}, converter Converter)
- func AddConversionByType(srcType reflect.Type, targetType reflect.Type, converter Converter)
- func AddNoTraverseType(i ...interface{})
- func Clone(s interface{}) (interface{}, error)
- func Copy(dst, src interface{}) []error
- func Fields(s interface{}) ([]reflect.StructField, error)
- func Get(s interface{}, name string) (interface{}, error)
- func HasZero(s interface{}) bool
- func IsZero(s interface{}) bool
- func IsZeroInFields(s interface{}, names ...string) (string, bool)
- func Kind(s interface{}, name string) (reflect.Kind, error)
- func Map(s interface{}) (map[string]interface{}, error)
- func RemoveConversion(in interface{}, out interface{})
- func RemoveNoTraverseType(i ...interface{})
- func Set(s interface{}, name string, value interface{}) error
- func Tag(s interface{}, name string) (reflect.StructTag, error)
- func Tags(s interface{}) (map[string]reflect.StructTag, error)
- type Converter
Examples ¶
Constants ¶
const ( // TagName is used to mention field options for go-model library. // // Example: // -------- // BookCount int `model:"bookCount"` // ArchiveInfo StoreInfo `model:"archiveInfo,notraverse"` TagName = "model" // OmitField value is used to omit field(s) from processing OmitField = "-" // OmitEmpty option is used skip field(s) from output if it's zero value OmitEmpty = "omitempty" // NoTraverse option makes sure the go-model library to not to traverse inside the struct object. // However, the field value will be evaluated or processed by library. NoTraverse = "notraverse" )
Variables ¶
var (
// Version # of go-model library
Version = "1.0"
)
Functions ¶
func AddConversion ¶
func AddConversion(in interface{}, out interface{}, converter Converter)
AddConversion mothod allows registering a custom `Converter` into the global `converterMap` by supplying pointers of the target types.
Example ¶
Register a custom `Converter` to allow conversions from `int` to `string`.
AddConversion((*int)(nil), (*string)(nil), func(in reflect.Value) (reflect.Value, error) { return reflect.ValueOf(strconv.FormatInt(in.Int(), 10)), nil }) type StructA struct { Mixed string } type StructB struct { Mixed int } src := StructB{Mixed: 123} dst := StructA{} errs := Copy(&dst, &src) if errs != nil { panic(errs) } fmt.Printf("%v", dst)
Output: {123}
Example (DestinationPointer) ¶
Register a custom `Converter` to allow conversions from `int` to `*string`.
AddConversion((*int)(nil), (**string)(nil), func(in reflect.Value) (reflect.Value, error) { str := strconv.FormatInt(in.Int(), 10) return reflect.ValueOf(&str), nil }) type StructA struct { Mixed *string } type StructB struct { Mixed int } src := StructB{Mixed: 123} dst := StructA{} errs := Copy(&dst, &src) if errs != nil { panic(errs[0]) } fmt.Printf("%v", *dst.Mixed)
Output: 123
Example (DestinationPointerByType) ¶
Register a custom `Converter` to allow conversions from `int` to `*string` by passing types.
srcType := reflect.TypeOf((*int)(nil)).Elem() targetType := reflect.TypeOf((**string)(nil)).Elem() AddConversionByType(srcType, targetType, func(in reflect.Value) (reflect.Value, error) { str := strconv.FormatInt(in.Int(), 10) return reflect.ValueOf(&str), nil }) type StructA struct { Mixed *string } type StructB struct { Mixed int } src := StructB{Mixed: 123} dst := StructA{} errs := Copy(&dst, &src) if errs != nil { panic(errs[0]) } fmt.Printf("%v", *dst.Mixed)
Output: 123
Example (SourcePointer) ¶
Register a custom `Converter` to allow conversions from `*int` to `string`.
AddConversion((**int)(nil), (*string)(nil), func(in reflect.Value) (reflect.Value, error) { return reflect.ValueOf(strconv.FormatInt(in.Elem().Int(), 10)), nil }) type StructA struct { Mixed string } type StructB struct { Mixed *int } val := 123 src := StructB{Mixed: &val} dst := StructA{} errs := Copy(&dst, &src) if errs != nil { panic(errs[0]) } fmt.Printf("%v", dst)
Output: {123}
func AddConversionByType ¶
AddConversionByType allows registering a custom `Converter` into golbal `converterMap` by types.
func AddNoTraverseType ¶
func AddNoTraverseType(i ...interface{})
AddNoTraverseType method adds the Go Lang type into global `NoTraverseTypeList`. The type(s) from list is considered as "No Traverse" type by go-model library for model mapping process. See also `RemoveNoTraverseType()` method.
model.AddNoTraverseType(time.Time{}, &time.Time{}, os.File{}, &os.File{})
Default NoTraverseTypeList: time.Time{}, &time.Time{}, os.File{}, &os.File{}, http.Request{}, &http.Request{}, http.Response{}, &http.Response{}
func Clone ¶
func Clone(s interface{}) (interface{}, error)
Clone method creates a clone of given `struct` object. As you know go-model does, deep processing. So all field values you get in the result.
Example: input := SampleStruct { /* input struct field values go here */ } clonedObj := model.Clone(input) fmt.Printf("\nCloned Object: %#v\n", clonedObj)
Note: [1] Two dimensional slice type is not supported yet.
A "model" tag with the value of "-" is ignored by library for processing.
Example: // Field is ignored while processing BookCount int `model:"-"` BookCode string `model:"-"`
A "model" tag value with the option of "omitempty"; library will not clone those values into result struct object.
Example: // Field is not cloned into 'result' if it's empty/zero value ArchiveInfo BookArchive `model:"archiveInfo,omitempty"` Region BookLocale `model:",omitempty,notraverse"`
A "model" tag value with the option of "notraverse"; library will not traverse inside the struct object. However, the field value will be evaluated whether it's zero value or not, and then cloned to the result accordingly.
Example: // Field is not traversed but value is evaluated/processed ArchiveInfo BookArchive `model:"archiveInfo,notraverse"` Region BookLocale `model:",notraverse"`
func Copy ¶
func Copy(dst, src interface{}) []error
Copy method copies all the exported field values from source `struct` into destination `struct`. The "Name", "Type" and "Kind" is should match to qualify a copy. One exception though; if the destination field type is "interface{}" then "Type" and "Kind" doesn't matter, source value gets copied to that destination field.
Example: src := SampleStruct { /* source struct field values go here */ } dst := SampleStruct {} errs := model.Copy(&dst, src) if errs != nil { fmt.Println("Errors:", errs) }
Note: [1] Copy process continues regardless of the case it qualifies or not. The non-qualified field(s) gets added to '[]error' that you will get at the end. [2] Two dimensional slice type is not supported yet.
A "model" tag with the value of "-" is ignored by library for processing.
Example: // Field is ignored while processing BookCount int `model:"-"` BookCode string `model:"-"`
A "model" tag value with the option of "omitempty"; library will not copy those values into destination struct object. It may be handy for partial put or patch update request scenarios; if you don't want to copy empty/zero value into destination object.
Example: // Field is not copy into 'dst' if it's empty/zero value ArchiveInfo BookArchive `model:"archiveInfo,omitempty"` Region BookLocale `model:",omitempty,notraverse"`
A "model" tag value with the option of "notraverse"; library will not traverse inside the struct object. However, the field value will be evaluated whether it's zero value or not, and then copied to the destination object accordingly.
Example: // Field is not traversed but value is evaluated/processed ArchiveInfo BookArchive `model:"archiveInfo,notraverse"` Region BookLocale `model:",notraverse"`
func Fields ¶
func Fields(s interface{}) ([]reflect.StructField, error)
Fields method returns the exported struct fields from the given `struct`.
Example: src := SampleStruct { /* source struct field values go here */ } fields, _ := model.Fields(src) for _, f := range fields { tag := newTag(f.Tag.Get("model")) fmt.Println("Field Name:", f.Name, "Tag Name:", tag.Name, "Tag Options:", tag.Options) }
func Get ¶
Get method returns a field value from `struct` by field name.
Example: src := SampleStruct { BookCount int `json:"-"` BookCode string `json:"-"` ArchiveInfo BookArchive `json:"archive_info,omitempty"` Region BookLocale `json:"region,omitempty"` } value, err := model.Get(src, "ArchiveInfo") fmt.Println("Field Value:", value) fmt.Println("Error:", err)
Note: Get method does not honor model tag annotations. Get simply access value on exported fields.
func HasZero ¶
func HasZero(s interface{}) bool
HasZero method returns `true` if any one of the exported fields in a given `struct` is zero value otherwise `false`. If input is not a struct, method returns `false`.
A "model" tag with the value of "-" is ignored by library for processing.
Example: // Field is ignored by go-model processing BookCount int `model:"-"` BookCode string `model:"-"`
A "model" tag value with the option of "notraverse"; library will not traverse inside the struct object. However, the field value will be evaluated whether it's zero value or not.
Example: // Field is not traversed but value is evaluated/processed ArchiveInfo BookArchive `model:"archiveInfo,notraverse"` Region BookLocale `model:",notraverse"`
func IsZero ¶
func IsZero(s interface{}) bool
IsZero method returns `true` if all the exported fields in a given `struct` are zero value otherwise `false`. If input is not a struct, method returns `false`.
A "model" tag with the value of "-" is ignored by library for processing.
Example: // Field is ignored by go-model processing BookCount int `model:"-"` BookCode string `model:"-"`
A "model" tag value with the option of "notraverse"; library will not traverse inside the struct object. However, the field value will be evaluated whether it's zero value or not.
Example: // Field is not traversed but value is evaluated/processed ArchiveInfo BookArchive `model:"archiveInfo,notraverse"` Region BookLocale `model:",notraverse"`
func IsZeroInFields ¶
IsZeroInFields method verifies the value for the given list of field names against given struct. Method returns `Field Name` and `true` for the zero value field. Otherwise method returns empty `string` and `false`.
Note: [1] This method doesn't traverse nested and embedded `struct`, instead it just evaluates that `struct`. [2] If given field is not exists in the struct, method moves on to next field
A "model" tag with the value of "-" is ignored by library for processing.
Example: // Field is ignored by go-model processing BookCount int `model:"-"` BookCode string `model:"-"`
func Kind ¶
Kind method returns `reflect.Kind` for the given field name from the `struct`.
Example: src := SampleStruct { BookCount int `json:"-"` BookCode string `json:"-"` ArchiveInfo BookArchive `json:"archive_info,omitempty"` Region BookLocale `json:"region,omitempty"` } fieldKind, _ := model.Kind(src, "ArchiveInfo") fmt.Println("Field kind:", fieldKind)
func Map ¶
Map method converts all the exported field values from the given `struct` into `map[string]interface{}`. In which the keys of the map are the field names and the values of the map are the associated values of the field.
Example: src := SampleStruct { /* source struct field values go here */ } err := model.Map(src) if err != nil { fmt.Println("Error:", err) }
Note: [1] Two dimensional slice type is not supported yet.
The default 'Key Name' string is the struct field name. However, it can be changed in the struct field's tag value via "model" tag.
Example: // Now field 'Key Name' is customized BookTitle string `model:"bookTitle"`
A "model" tag with the value of "-" is ignored by library for processing.
Example: // Field is ignored while processing BookCount int `model:"-"` BookCode string `model:"-"`
A "model" tag value with the option of "omitempty"; library will not include those values while converting to map[string]interface{}. If it's empty/zero value.
Example: // Field is not included in result map if it's empty/zero value ArchivedDate time.Time `model:"archivedDate,omitempty"` Region BookLocale `model:",omitempty,notraverse"`
A "model" tag value with the option of "notraverse"; library will not traverse inside the struct object. However, the field value will be evaluated whether it's zero value or not, and then added to the result map accordingly.
Example: // Field is not traversed but value is evaluated/processed ArchivedDate time.Time `model:"archivedDate,notraverse"` Region BookLocale `model:",notraverse"`
func RemoveConversion ¶
func RemoveConversion(in interface{}, out interface{})
RemoveConversion registered conversions
func RemoveNoTraverseType ¶
func RemoveNoTraverseType(i ...interface{})
RemoveNoTraverseType method is used to remove Go Lang type from the `NoTraverseTypeList`. See also `AddNoTraverseType()` method.
model.RemoveNoTraverseType(http.Request{}, &http.Request{})
func Set ¶
Set method sets a value into field on struct by field name.
Example: src := SampleStruct { BookCount int `json:"-"` BookCode string `json:"-"` ArchiveInfo BookArchive `json:"archive_info,omitempty"` Region BookLocale `json:"region,omitempty"` } bookLocale := BookLocale { Locale: "en-US", Language: "en", Region: "US", } err := model.Set(&src, "Region", bookLocale) fmt.Println("Error:", err)
Note: Set method does not honor model tag annotations. Set simply given value by field name on exported fields.
func Tag ¶
Tag method returns the exported struct field `Tag` value from the given struct.
Example: src := SampleStruct { BookCount int `json:"-"` BookCode string `json:"-"` ArchiveInfo BookArchive `json:"archive_info,omitempty"` Region BookLocale `json:"region,omitempty"` } tag, _ := model.Tag(src, "ArchiveInfo") fmt.Println("Tag Value:", tag.Get("json")) // Output: Tag Value: archive_info,omitempty
func Tags ¶
Tags method returns the exported struct fields `Tag` value from the given struct.
Example: src := SampleStruct { BookCount int `json:"-"` BookCode string `json:"-"` ArchiveInfo BookArchive `json:"archive_info,omitempty"` Region BookLocale `json:"region,omitempty"` } tags, _ := model.Tags(src) fmt.Println("Tags:", tags)