forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.go
199 lines (171 loc) · 4.47 KB
/
init.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package structs
import (
"errors"
"reflect"
"github.com/gookit/goutil/internal/varexpr"
"github.com/gookit/goutil/reflects"
"github.com/gookit/goutil/strutil"
)
const defaultInitTag = "default"
// InitOptFunc define
type InitOptFunc func(opt *InitOptions)
// InitOptions struct
type InitOptions struct {
// TagName default value tag name. tag: default
TagName string
// ParseEnv var name on default value. eg: `default:"${APP_ENV}"`
//
// default: false
ParseEnv bool
// ValueHook before set value hook TODO
ValueHook func(val string) any
}
// Init struct default value by field "default" tag.
func Init(ptr any, optFns ...InitOptFunc) error {
return InitDefaults(ptr, optFns...)
}
// InitDefaults init struct default value by field "default" tag.
//
// TIPS:
//
// Support init field types: string, bool, intX, uintX, floatX, array, slice
//
// Example:
//
// type User1 struct {
// Name string `default:"inhere"`
// Age int32 `default:"30"`
// }
//
// u1 := &User1{}
// err = structs.InitDefaults(u1)
// fmt.Printf("%+v\n", u1) // Output: {Name:inhere Age:30}
func InitDefaults(ptr any, optFns ...InitOptFunc) error {
rv := reflect.ValueOf(ptr)
if !reflects.IsValidPtr(rv) {
return errors.New("must be provider an pointer value")
}
rv = rv.Elem()
if rv.Kind() != reflect.Struct {
return errors.New("must be provider an struct value")
}
opt := &InitOptions{TagName: defaultInitTag}
for _, fn := range optFns {
fn(opt)
}
return initDefaults(rv, opt)
}
func initDefaults(rv reflect.Value, opt *InitOptions) error {
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
sf := rt.Field(i)
// skip don't exported field
if IsUnexported(sf.Name) {
continue
}
val, hasTag := sf.Tag.Lookup(opt.TagName)
if !hasTag || val == "-" {
continue
}
fv := rv.Field(i)
if fv.Kind() == reflect.Struct {
if err := initDefaults(fv, opt); err != nil {
return err
}
continue
}
// Skip init on field has value. but will check slice and pointer field
if !fv.IsZero() {
// special: handle for pointer struct field
if fv.Kind() == reflect.Pointer {
fv = fv.Elem()
if fv.Kind() == reflect.Struct {
if err := initDefaults(fv, opt); err != nil {
return err
}
}
} else if fv.Kind() == reflect.Slice {
el := sf.Type.Elem()
if el.Kind() == reflect.Pointer {
el = el.Elem()
}
// init sub struct in slice. like `[]SubStruct` or `[]*SubStruct`
if el.Kind() == reflect.Struct && fv.Len() > 0 {
for i := 0; i < fv.Len(); i++ {
subFv := reflect.Indirect(fv.Index(i))
if err := initDefaults(subFv, opt); err != nil {
return err
}
}
}
}
continue
}
// handle for pointer field
if fv.Kind() == reflect.Pointer {
if fv.IsNil() {
fv.Set(reflect.New(fv.Type().Elem()))
}
fv = fv.Elem()
if fv.Kind() == reflect.Struct {
if err := initDefaults(fv, opt); err != nil {
return err
}
continue
}
} else if fv.Kind() == reflect.Slice {
el := sf.Type.Elem()
isPtr := el.Kind() == reflect.Pointer
if isPtr {
el = el.Elem()
}
// init sub struct in slice. like `[]SubStruct` or `[]*SubStruct`
if el.Kind() == reflect.Struct {
// up: if slice elem is struct and slice len=0, will be skip init default value
if fv.Len() == 0 {
continue
}
// make sub-struct and init. like: `SubStruct`
subFv := reflect.New(el)
subFvE := subFv.Elem()
if err := initDefaults(subFvE, opt); err != nil {
return err
}
// make new slice and set value.
newFv := reflect.MakeSlice(reflect.SliceOf(sf.Type.Elem()), 0, 1)
if isPtr {
newFv = reflect.Append(newFv, subFv)
} else {
newFv = reflect.Append(newFv, subFvE)
}
fv.Set(newFv)
continue
}
}
if err := initDefaultValue(fv, val, opt.ParseEnv); err != nil {
return err
}
}
return nil
}
func initDefaultValue(fv reflect.Value, val string, parseEnv bool) error {
if val == "" || !fv.CanSet() {
return nil
}
// parse env var
if parseEnv {
val = varexpr.SafeParse(val)
}
var anyVal any = val
// simple slice: convert simple kind(string,intX,uintX,...) to slice. eg: "1,2,3" => []int{1,2,3}
if reflects.IsArrayOrSlice(fv.Kind()) && reflects.IsSimpleKind(reflects.SliceElemKind(fv.Type())) {
ss := strutil.SplitTrimmed(val, ",")
valRv, err := reflects.ConvSlice(reflect.ValueOf(ss), fv.Type().Elem())
if err == nil {
reflects.SetRValue(fv, valRv)
}
return err
}
// set value
return reflects.SetValue(fv, anyVal)
}