Documentation
¶
Overview ¶
Example ¶
package main
import (
"fmt"
"sort"
"time"
"github.com/worldline-go/struct2"
"github.com/worldline-go/struct2/types"
)
func SortPrint(m map[string]interface{}) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("Type: %T, Value: %v\n", m[k], m[k])
}
}
func main() {
type ColorGroup struct {
ID int `struct:"id"`
Name string `struct:"name"`
Colors []string `struct:"colors"`
Date types.Time `struct:"time"`
}
d, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
Date: types.Time{Time: d},
}
decoder := struct2.Decoder{}
result := decoder.Map(group)
// fmt.Printf("%#v", result)
SortPrint(result)
}
Output: Type: []string, Value: [Crimson Red Ruby Maroon] Type: int, Value: 1 Type: string, Value: Reds Type: time.Time, Value: 2006-01-02 15:04:05 +0000 UTC
Example (CustomHook) ¶
package main
import (
"fmt"
"reflect"
"github.com/worldline-go/struct2"
)
func main() {
type ColorGroup struct {
Name string `db:"name"`
Count int `db:"count"`
}
group := ColorGroup{
Name: "DeepCore",
}
decoder := struct2.Decoder{
TagName: "db",
Hooks: []struct2.HookFunc{func(v reflect.Value) (interface{}, error) {
if v.Kind() == reflect.String {
return "str_" + v.Interface().(string), nil
}
return nil, struct2.ErrContinueHook
}},
}
result := decoder.Map(group)
fmt.Printf("%v", result["name"])
}
Output: str_DeepCore
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrContinueHook = errors.New("continue to decode")
ErrContinueHook usable with HookFunc.
Functions ¶
func Ptr2Concrete ¶
func Ptr2Concrete(val interface{}) interface{}
Types ¶
type Decoder ¶
type Decoder struct {
// Tagname to lookup struct's field tag.
TagName string // default is 'struct'
// Hooks function run before decode and enable to change of data.
Hooks []HookFunc
}
Decoder is main struct of struct2, holds config and functions.
func (*Decoder) MapOmitNested ¶
MapOmitNested converts given struct to the map[string]interface{} without looking nested object.
Click to show internal directories.
Click to hide internal directories.