diff options
author | Pacien TRAN-GIRARD | 2015-02-14 11:24:17 +0100 |
---|---|---|
committer | Pacien TRAN-GIRARD | 2015-02-14 11:27:36 +0100 |
commit | 8e99baedf2c3e433750c2f51681f3c9d15d412be (patch) | |
tree | 3fa0ff3ea4823a408dadceb14fcd51ddc16c2aa8 /mapper.go | |
parent | 8b1f88ce72ef8496879395e7f04b676e6a16e07a (diff) | |
download | go-envcfg-8e99baedf2c3e433750c2f51681f3c9d15d412be.tar.gz |
First version
Diffstat (limited to 'mapper.go')
-rw-r--r-- | mapper.go | 86 |
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 @@ | |||
1 | package envcfg | ||
2 | |||
3 | import ( | ||
4 | "os" | ||
5 | "reflect" | ||
6 | "strconv" | ||
7 | "strings" | ||
8 | ) | ||
9 | |||
10 | func 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 | |||
27 | func 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 | |||
57 | func 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 | |||
71 | func 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 | } | ||