@@ -2,6 +2,7 @@ package gone
2
2
3
3
import (
4
4
"encoding/json"
5
+ "errors"
5
6
"os"
6
7
"reflect"
7
8
"strconv"
@@ -113,7 +114,24 @@ func (s *EnvConfigure) Get(key string, v any, defaultVal string) error {
113
114
return SetValue (rv , v , env )
114
115
}
115
116
117
+ var UnsupportedError = NewInnerError ("Unsupported type by EnvConfigure" , ConfigError )
118
+
119
+ // SetValue sets the value of a pointer to a Go type based on the provided value and environment variable.
120
+ // Deprecated use SetPointerValue or SetValueByReflect instead
116
121
func SetValue (rv reflect.Value , v any , value string ) error {
122
+ err := SetPointerValue (v , value )
123
+ if err != nil {
124
+ if errors .Is (err , UnsupportedError ) {
125
+ return SetValueByReflect (rv , value )
126
+ } else {
127
+ return ToError (err )
128
+ }
129
+ }
130
+ return nil
131
+ }
132
+
133
+ // SetPointerValue sets the value of a pointer to a Go type based on the provided value and environment variable.
134
+ func SetPointerValue (v any , value string ) error {
117
135
// Type switch to handle different pointer types
118
136
switch ptr := v .(type ) {
119
137
// String type
@@ -215,16 +233,17 @@ func SetValue(rv reflect.Value, v any, value string) error {
215
233
* ptr = val
216
234
217
235
default :
218
- return setValueByReflectValue ( rv , v , value )
236
+ return UnsupportedError
219
237
}
220
238
return nil
221
239
}
222
240
223
- func setValueByReflectValue (rv reflect.Value , v any , value string ) error {
241
+ // SetValueByReflect sets the value of a pointer to a Go type based on the provided value and environment variable.
242
+ func SetValueByReflect (rv reflect.Value , value string ) error {
224
243
k := rv .Elem ().Kind ()
225
244
switch k {
226
245
case reflect .Struct , reflect .Slice , reflect .Map :
227
- return ToError (json .Unmarshal ([]byte (value ), v ))
246
+ return ToError (json .Unmarshal ([]byte (value ), rv . Interface () ))
228
247
case reflect .String :
229
248
rv .Elem ().SetString (value )
230
249
case reflect .Int :
@@ -310,8 +329,7 @@ func setValueByReflectValue(rv reflect.Value, v any, value string) error {
310
329
rv .Elem ().SetBool (val )
311
330
312
331
default :
313
- // Struct and unsupported types
314
- return NewInnerError ("Unsupported type by EnvConfigure" , ConfigError )
332
+ return UnsupportedError
315
333
}
316
334
return nil
317
335
}
0 commit comments