model

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

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

Go to latest
Published: Apr 3, 2018 License: MIT Imports: 7 Imported by: 0

README ¶

go-model Build Status codecov GoReport Version GoDoc License

Robust & Easy to use model mapper and utility methods for Go struct. Typical methods increase productivity and make Go development more fun 😄

v1.0 released and tagged on May 22, 2017

go-model tested with Go v1.2 and above.

Features

go-model library provides handy methods to process struct with below highlighted features. It's born from typical need while developing Go application or utility. I hope it's helpful to Go community!

  • Embedded/Anonymous struct
  • Multi-level nested struct/map/slice
  • Pointer and non-pointer within struct/map/slice
  • Struct within map and slice
  • Embedded/Anonymous struct fields appear in map at same level as represented by Go
  • Interface within struct/map/slice
  • Get struct field reflect.Kind by field name
  • Get all the struct field tags (reflect.StructTag) or selectively by field name
  • Get all reflect.StructField for given struct instance
  • Get or Set by individual field name on struct
  • Add global no traverse type to the list or use notraverse option in the struct field
  • Options to name map key, omit empty fields, and instruct not to traverse with struct/map/slice
  • Conversions between mixed non-pointer types - add custom conversation method, refer to usage

Installation

Stable Version - Production Ready

Please refer section Versioning for detailed info.

# install the library
go get -u gopkg.in/jeevatkm/go-model.v1
Latest Version - Development Edge
# install the latest & greatest library
go get -u github.com/jeevatkm/go-model

It might be beneficial for your project 😄

go-model author also published following projects to Go Community.

  • aah framework - A secure, flexible, rapid Go web framework.
  • go-resty - Simple HTTP and REST client for Go.

Usage

Import go-model into your code and refer it as model. Have a look on model test cases to know more possibilities.

import (
  "gopkg.in/jeevatkm/go-model.v1"
)
Supported Methods
Copy Method

How do I copy my struct object into another? Not to worry, go-model does deep copy.

// let's say you have just decoded/unmarshalled your request body to struct object.
tempProduct, _ := myapp.ParseJSON(request.Body)

product := Product{}

// tag your Product fields with appropriate options like
// -, omitempty, notraverse to get desired result.
// Not to worry, go-model does deep copy :)
errs := model.Copy(&product, tempProduct)
fmt.Println("Errors:", errs)

fmt.Printf("\nSource: %#v\n", tempProduct)
fmt.Printf("\nDestination: %#v\n", product)
Map Method

I want to convert my struct into Map (map[string]interface{}). Sure, go-model does deep convert.

// tag your SearchResult fields with appropriate options like
// -, name, omitempty, notraverse to get desired result.
sr, _ := myapp.GetSearchResult( /* params here */ )

// Embedded/Anonymous struct fields appear in map at same level as represented by Go
srchResMap, err := model.Map(sr)
fmt.Println("Error:", err)

fmt.Printf("\nSearch Result Map: %#v\n", srchResMap)
Clone Method

I would like to clone my struct object. That's nice, you know go-model does deep processing.

input := Product { /* Product struct field values go here */ }

// have your struct fields tagged appropriately. Options like
// -, name, omitempty, notraverse to get desired result.
clonedObj := model.Clone(input)

// let's see the result
fmt.Printf("\nCloned Object: %#v\n", clonedObj)
IsZero Method

I want to check my struct object is empty or not. Of course, go-model does deep zero check.

// let's say you have just decoded/unmarshalled your request body to struct object.
productInfo, _ := myapp.ParseJSON(request.Body)

// wanna check productInfo is empty or not
isEmpty := model.IsZero(productInfo)

// tag your ProductInfo fields with appropriate options like
// -, omitempty, notraverse to get desired result.
fmt.Println("Hey, I have all fields zero value:", isEmpty)
HasZero Method

I want to check my struct object has any zero/empty value. Of course, go-model does deep zero check.

// let's say you have just decoded/unmarshalled your request body to struct object.
productInfo, _ := myapp.ParseJSON(request.Body)

// wanna check productInfo is empty or not
isEmpty := model.HasZero(productInfo)

// tag your ProductInfo fields with appropriate options like
// -, omitempty, notraverse to get desired result.
fmt.Println("Hey, I have zero values:", isEmpty)
IsZeroInFields Method

Is it possible to check to particular fields has zero/empty values. Of-course you can.

// let's say you have just decoded/unmarshalled your request body to struct object.
product, _ := myapp.ParseJSON(request.Body)

// check particular fields has zero value or not
fieldName, isEmpty := model.IsZeroInFields(product, "SKU", "Title", "InternalIdentifier")

fmt.Println("Empty Field Name:", fieldName)
fmt.Println("Yes, I have zero value:", isEmpty)
Fields Method

You wanna all the fields from struct, Yes you can have it :)

src := SampleStruct {
  /* struct fields go here */
}

fields, _ := model.Fields(src)
fmt.Println("Fields:", fields)
Kind Method

go-model library provides an ability to know the reflect.Kind in as easy way.

src := SampleStruct {
  /* struct fields go here */
}

fieldKind, _ := model.Kind(src, "BookingInfoPtr")
fmt.Println("Field kind:", fieldKind)
Tag Method

I want to get Go lang supported Tag value from my struct. Yes, it is easy to get it.

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
Tags Method

I would like to get all the fields Tag values from my struct. It's easy.

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)
Get Method

I want to get value by field name on my struct. Yes, it is easy to get it.

src := SampleStruct {
	BookCount: 100,
	BookCode:  "GHT67HH00",
}

value, _ := model.Get(src, "BookCode")
fmt.Println("Value:", value)

// Output:
Value: GHT67HH00
Set Method

I want to set value by field name on my struct. Yes, it is easy to get it.

src := SampleStruct {
	BookCount: 100,
	BookCode:  "GHT67HH00",
}

err := model.Set(&src, "BookCount", 200)
fmt.Println("Error:", err)
AddNoTraverseType & RemoveNoTraverseType Methods

There are scenarios, where you want the object values but not to traverse/look inside the struct object. Use notraverse option in the model tag for those fields or Add it NoTraverseTypeList. Customize it as per your need.

Default NoTraverseTypeList has these types time.Time{}, &time.Time{}, os.File{}, &os.File{}, http.Request{}, &http.Request{}, http.Response{}, &http.Response{}.

// If you have added your type into list then you need not mention `notraverse` option for those types.

// Adding type into NoTraverseTypeList
model.AddNoTraverseType(time.Location{}, &time.Location{})

// Removing type from NoTraverseTypeList
model.RemoveNoTraverseType(time.Location{}, &time.Location{})
AddConversion & RemoveConversion Methods

This example registers a custom conversion from the int to the string type.

AddConversion((*int)(nil), (*string)(nil), func(in reflect.Value) (reflect.Value, error) {
		return reflect.ValueOf(strconv.FormatInt(in.Int(), 10)), nil
	})

If a an integer field on the source struct matches the name of a string field on the target struct, the provided Converter method is invoked.

Note that if you want to register a converter from int to *string you will have to provide a pointer to a pointer as destination type ( (**string)(nil) ).

More examples can be found in the AddConversion godoc.

Versioning

go-model releases versions according to Semantic Versioning

gopkg.in/jeevatkm/go-model.vX points to appropriate tag versions; X denotes version number and it's a stable release. It's recommended to use version, for eg. gopkg.in/jeevatkm/go-model.v0. Development takes place at the master branch. Although the code in master should always compile and test successfully, it might break API's. We aim to maintain backwards compatibility, but API's and behaviour might be changed to fix a bug.

Contributing

Welcome! If you find any improvement or issue you want to fix, feel free to send a pull request. I like pull requests that include test cases for fix/enhancement. I have done my best to bring pretty good code coverage. Feel free to write tests.

BTW, I'd like to know what you think about go-model. Kindly open an issue or send me an email; it'd mean a lot to me.

Author

Jeevanandam M. - jeeva@myjeeva.com

Contributors

Have a look on Contributors page.

License

go-model released under MIT license, refer LICENSE file.

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 ¶

Examples ¶

Constants ¶

View Source
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 ¶

View Source
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 ¶

func AddConversionByType(srcType reflect.Type, targetType reflect.Type, converter Converter)

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 ¶

func Get(s interface{}, name string) (interface{}, error)

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 ¶

func IsZeroInFields(s interface{}, names ...string) (string, bool)

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 ¶

func Kind(s interface{}, name string) (reflect.Kind, error)

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 ¶

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

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 ¶

func Set(s interface{}, name string, value interface{}) error

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 ¶

func Tag(s interface{}, name string) (reflect.StructTag, error)

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 ¶

func Tags(s interface{}) (map[string]reflect.StructTag, error)

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)

Types ¶

type Converter ¶

type Converter func(in reflect.Value) (reflect.Value, error)

Converter is used to provide custom mappers for a datatype pair.

Jump to

Keyboard shortcuts

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