-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample_stuct_test.go
More file actions
59 lines (49 loc) · 1.13 KB
/
example_stuct_test.go
File metadata and controls
59 lines (49 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package struct2_test
import (
"fmt"
"reflect"
"time"
"github.com/worldline-go/struct2"
)
func Example_mapToStruct() {
type SubCfg struct {
Enabled bool `cfg:"enabled"`
}
type Config struct {
Name string `cfg:"name"`
Count int `cfg:"count"`
Sub SubCfg `cfg:"sub"`
Time time.Duration `cfg:"time"`
}
decoder := struct2.Decoder{
TagName: "cfg",
HooksDecode: []struct2.HookDecodeFunc{func(in reflect.Type, out reflect.Type, data any) (any, error) {
if out == reflect.TypeFor[time.Duration]() {
switch in.Kind() {
case reflect.String:
return time.ParseDuration(data.(string))
}
}
return data, nil
}},
WeaklyTypedInput: true,
WeaklyIgnoreSeperator: true,
WeaklyDashUnderscore: true,
}
cfgMap := map[string]any{
"name": "Altay",
"count": "42",
"sub": map[string]any{
"enabled": "true",
},
"time": "1h30m",
}
var cfg Config
if err := decoder.Decode(cfgMap, &cfg); err != nil {
fmt.Printf("decode error: %v", err)
return
}
fmt.Printf("%v %v %v %v", cfg.Name, cfg.Count, cfg.Sub.Enabled, cfg.Time)
// Output:
// Altay 42 true 1h30m0s
}