generated from inherelab/go-pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
92 lines (78 loc) · 2.26 KB
/
options.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package properties
import "github.com/mitchellh/mapstructure"
// DefaultTagName for mapping data to struct.
var DefaultTagName = "properties"
// OpFunc custom option func
type OpFunc func(opts *Options)
// Options for config
type Options struct {
// Debug open debug mode
Debug bool
// ParseEnv parse ENV var name, default True. eg: "${SHELL}"
ParseEnv bool
// ParseVar reference. eg: "${other.var.name}". default: true
ParseVar bool
// ParseTime string on binding struct. eg: 3s -> 3*time.Second
ParseTime bool
// TagName for binding data to struct. default: properties
TagName string
// TrimValue trim "\n" for value string. default: false
TrimValue bool
// InlineComment support split inline comments. default: false
//
// allow chars: #, //
InlineComment bool
// InlineSlice support parse the inline slice. eg: [23, 34]. default: false
InlineSlice bool
// MapStructConfig for binding data to struct.
MapStructConfig mapstructure.DecoderConfig
// BeforeCollect value handle func, you can return a new value.
BeforeCollect func(name string, val any) any
}
func (opts *Options) makeDecoderConfig() *mapstructure.DecoderConfig {
decConf := opts.MapStructConfig
// compatible with settings on opts.TagName
if decConf.TagName == "" {
decConf.TagName = opts.TagName
}
// parse time string on binding to struct
if opts.ParseTime || decConf.DecodeHook == nil {
decConf.DecodeHook = ValDecodeHookFunc()
}
return &decConf
}
func newDefaultOption() *Options {
return &Options{
ParseVar: true,
TagName: DefaultTagName,
// map struct config
MapStructConfig: mapstructure.DecoderConfig{
TagName: DefaultTagName,
// will auto convert string to int/uint
WeaklyTypedInput: true,
},
}
}
// WithDebug open debug mode
func WithDebug(opts *Options) {
opts.Debug = true
}
// ParseEnv open parse ENV var string.
func ParseEnv(opts *Options) {
opts.ParseEnv = true
}
// ParseTime open parse time string.
func ParseTime(opts *Options) {
opts.ParseTime = true
}
// ParseInlineSlice open parse inline slice
func ParseInlineSlice(opts *Options) {
opts.InlineSlice = true
}
// WithTagName custom tag name on binding struct
func WithTagName(tagName string) OpFunc {
return func(opts *Options) {
opts.TagName = tagName
opts.MapStructConfig.TagName = tagName
}
}