Go library for encoding native Go structures into generic map values.
Use go get.
go get -u github.com/things-go/structsThen import the structs package into your own code.
import"github.com/things-go/structs"Just like the standard lib strings, bytes and co packages, structs has many global functions to manipulate or organize your struct data. Lets define and declare a struct:
typeServerstruct {
Namestring`json:"name,omitempty"`IDintEnabledboolusers []string// not exported
http.Server// embedded
}
server:=&Server{
Name: "gopher",
ID: 123456,
Enabled: true,
}Here is an example:
// Convert a struct to a map[string]interface{}// => {"Name":"gopher", "ID":123456, "Enabled":true}m:=structs.Map(server)
// Convert the values of a struct to a []interface{}// => ["gopher", 123456, true]v:=structs.Values(server)
// Convert the names of a struct to a []string// (see "Names methods" for more info about fields)n:=structs.Names(server)
// Convert the values of a struct to a []*Field// (see "Field methods" for more info about fields)f:=structs.Fields(server)
// Return the struct name => "Server"n:=structs.Name(server)
// Check if any field of a struct is initialized or not.h:=structs.HasZero(server)
// Check if all fields of a struct is initialized or not.z:=structs.IsZero(server)
// Check if server is a struct or a pointer to structi:=structs.IsStruct(server)Only public fields will be processed. So fields starting with lowercase will be ignored.
typeAAstruct {
Idint64`map:"id"`Namestring`map:"name"`
}We can give the field a tag to specify another name to be used as the key.
typeAAstruct {
Ignorestring`map:"-"`
}If we give the special tag "-" to a field, it will be ignored.
typeAAstruct {
Descstring`map:"desc,omitempty"`
}If tag option is "omitempty", this field will not appear in the map if the value is empty. Empty values are 0, false, "", nil, empty array and empty map.
typeAAstruct {
// Field is not processed further by this package.Field*http.Request`map:",omitnested"`
}A value with the option of "omitnested" stops iterating further if the type is a struct. it do not converted value if a value are no exported fields, ie: time.Time
typeAAstruct {
Idint64`map:"id,string"`Pricefloat32`map:"price,string"`
}If tag option is "string", this field will be converted to string type. Encode will put the original value to the map if the conversion is failed.
This project is under MIT License. See the LICENSE file for the full license text.