-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainGetEnv.go
65 lines (55 loc) · 1.66 KB
/
mainGetEnv.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
package utils
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
func GetEnv[T comparable](key string, defaultValue T) T {
value, exists := os.LookupEnv(key)
if !exists {
return defaultValue
}
defaultValueType := reflect.TypeOf(defaultValue)
switch defaultValueType.Kind() {
case reflect.String:
return interface{}(value).(T)
case reflect.Slice:
valueSlice := strings.Split(value, ",")
sliceType := defaultValueType.Elem()
slice := reflect.MakeSlice(reflect.SliceOf(sliceType), len(valueSlice), len(valueSlice))
for i, v := range valueSlice {
sliceValue := convert(v, sliceType)
slice.Index(i).Set(reflect.ValueOf(sliceValue))
}
return slice.Interface().(T)
default:
return convert(value, defaultValueType).Interface().(T)
}
}
func convert(value string, targetType reflect.Type) reflect.Value {
switch targetType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if parsedValue, err := strconv.ParseInt(value, 10, 64); err == nil {
return reflect.ValueOf(parsedValue).Convert(targetType)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if parsedValue, err := strconv.ParseUint(value, 10, 64); err == nil {
return reflect.ValueOf(parsedValue).Convert(targetType)
}
case reflect.Bool:
if parsedValue, err := strconv.ParseBool(value); err == nil {
return reflect.ValueOf(parsedValue).Convert(targetType)
}
case reflect.String:
return reflect.ValueOf(value).Convert(targetType)
default:
return reflect.Zero(targetType)
}
return reflect.Zero(targetType)
}
func main() {
envVar := GetEnv("any string", "")
fmt.Println("The value of envVar:", envVar)
}