Go library for encoding native Go structures into generic map values.
Use go get.
go get -u github.com/things-go/structs
Then 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:
type Server struct {
Name string `json:"name,omitempty"`
ID int
Enabled bool
users []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 struct
i := structs.IsStruct(server)
Only public fields will be processed. So fields starting with lowercase will be ignored.
type AA struct {
Id int64 `map:"id"`
Name string `map:"name"`
}
We can give the field a tag to specify another name to be used as the key.
type AA struct {
Ignore string `map:"-"`
}
If we give the special tag "-" to a field, it will be ignored.
type AA struct {
Desc string `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.
type AA struct {
// 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
type AA struct {
Id int64 `map:"id,string"`
Price float32 `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.