aboutsummaryrefslogtreecommitdiff
path: root/mapper.go
diff options
context:
space:
mode:
Diffstat (limited to 'mapper.go')
-rw-r--r--mapper.go86
1 files changed, 86 insertions, 0 deletions
diff --git a/mapper.go b/mapper.go
new file mode 100644
index 0000000..ca6885b
--- /dev/null
+++ b/mapper.go
@@ -0,0 +1,86 @@
1package envcfg
2
3import (
4 "os"
5 "reflect"
6 "strconv"
7 "strings"
8)
9
10func getEnvName(n node) string {
11 name := n.properties.Tag.Get(TAG)
12 if name == "" {
13 name = n.properties.Name
14 }
15
16 abs, _ := strconv.ParseBool(n.properties.Tag.Get(ABS_TAG))
17 if !abs && n.parent != nil {
18 if n.parent.properties != nil {
19 parentName := getEnvName(*n.parent)
20 name = parentName + SEP + name
21 }
22 }
23
24 return strings.ToUpper(name)
25}
26
27func setValue(n node, v string) (node, error) {
28 switch n.value.Kind() {
29 case reflect.String:
30 n.value.SetString(v)
31
32 case reflect.Bool:
33 boolVal, err := strconv.ParseBool(v)
34 if err != nil {
35 return n, err
36 }
37 n.value.SetBool(boolVal)
38
39 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
40 intVal, err := strconv.ParseInt(v, 0, n.value.Type().Bits())
41 if err != nil {
42 return n, err
43 }
44 n.value.SetInt(intVal)
45
46 case reflect.Float32, reflect.Float64:
47 floatVal, err := strconv.ParseFloat(v, n.value.Type().Bits())
48 if err != nil {
49 return n, err
50 }
51 n.value.SetFloat(floatVal)
52 }
53
54 return n, nil
55}
56
57func setFieldValue(n node) (node, error) {
58 if n.value.Kind() == reflect.Struct {
59 setStructFields(n)
60 return n, nil
61 }
62
63 v := os.Getenv(getEnvName(n))
64 if v != "" {
65 return setValue(n, v)
66 }
67
68 return n, nil
69}
70
71func setStructFields(n node) (node, []error) {
72 t := n.value.Type()
73 errs := []error{}
74
75 for i := 0; i < n.value.NumField(); i++ {
76 v := n.value.Field(i)
77 p := t.Field(i)
78
79 _, err := setFieldValue(node{&n, &v, &p})
80 if err != nil {
81 errs = append(errs, err)
82 }
83 }
84
85 return n, errs
86}