-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconf.go
More file actions
69 lines (63 loc) · 1.65 KB
/
Copy pathconf.go
File metadata and controls
69 lines (63 loc) · 1.65 KB
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
package env
import (
"encoding/json"
"os"
"reflect"
"strconv"
"strings"
)
// Conf populates a json object applying tag:default conf values
// that are overloaded by the file source when configured at the
// primary level; no recurrsion support
//
// type Example struct {
// Text string `json:"text,omitempty"`
// Number int `json:"number,omitempty" default:"10"`
// Show bool `json:"show,omitempty" default:"on"`
// }
//
// supports: string, int, bool
func Conf(cfg any, path string) {
// conf.json {"text":"hello","number":5}
// var cfg Example
// env.Conf(&cfg, "conf.json")
// t.Log(cfg)
// === RUN TestConf
// conf_test.go:19: {hello 5 true}
// --- PASS: TestConf (0.00s)
v := reflect.Indirect(reflect.ValueOf(cfg))
if v.Type().Kind() == reflect.Struct {
for j := 0; j < v.NumField(); j++ {
if s, ok := v.Type().Field(j).Tag.Lookup("default"); ok {
switch v.Field(j).Kind() {
case reflect.String:
v.Field(j).SetString(s)
case reflect.Int, reflect.Int64:
n, _ := strconv.ParseInt(s, 10, 0)
v.Field(j).SetInt(n)
case reflect.Uint, reflect.Uint64:
n, _ := strconv.ParseUint(s, 10, 0)
v.Field(j).SetUint(n)
case reflect.Float32, reflect.Float64:
n, _ := strconv.ParseFloat(s, 64)
v.Field(j).SetFloat(n)
case reflect.Bool:
switch strings.ToLower(s) {
// case "off", "no", "false", "0":
// v.Field(j).SetBool(false)
case "on", "yes", "ok", "true", "1":
v.Field(j).SetBool(true)
}
}
}
}
}
// load json object configuration file
if len(path) > 0 {
f, err := os.Open(path)
if err == nil {
json.NewDecoder(f).Decode(&cfg)
f.Close()
}
}
}