-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsoncfg.go
105 lines (78 loc) · 2.43 KB
/
jsoncfg.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package jsoncfg
import (
"encoding/json"
"io/ioutil"
"log"
"strconv"
"strings"
"github.com/ieee0824/go-deepmerge"
)
type Jsonconfig struct {
Masterdata interface{}
}
// Interface was created but not used, was intended to make the class able to handle alternative configs sources and data fetching methods.
// This needs abit more work to be functional, but roughly illustrates the intended function.
type Configforge interface {
Get(string)
Loadfile(string)
Loadfiles(...string)
}
// Given a list of file names, read them in order and parse the files into a master data store
func (cfg *Jsonconfig) Loadfiles(files ...string) {
for _, file := range files {
file_raw, err := ioutil.ReadFile(file)
if err != nil {
log.Println("Error reading file:", err)
return
}
//fmt.Println("Reading : " + file)
//fmt.Println(string(file_raw))
cfg.Loadfile(file_raw)
}
}
// Read and load a individual JSON configuration files, given the file name
// decodes the JSON into a internal data struture and merges the new data structure
// with the existing master data structure
func (cfg *Jsonconfig) Loadfile(file_data []byte) {
var localdata interface{}
err := json.Unmarshal(file_data, &localdata)
if err != nil {
log.Println("Error decoding json:", err)
return
}
if cfg.Masterdata != nil {
// merge the data sets so that the data in localdata always overrides masterdata
merged_data, err := deepmerge.Merge(localdata, cfg.Masterdata)
if err != nil {
log.Println("Error merging data:", err)
return
}
cfg.Masterdata = merged_data
} else {
cfg.Masterdata = localdata
}
//fmt.Println(cfg.Masterdata)
}
// Reads a value from the master data structure, given a dot seperated key string
// For example "database.host" attempts to fetch the value stored in the master data
// structure.
func (cfg *Jsonconfig) Get(searchstr string) interface{} {
fragments := strings.Split(searchstr, ".")
datum := cfg.Masterdata
for _, fragment := range fragments {
// type switch to support arrays
switch datum.(type) {
case []interface{}:
index, err := strconv.Atoi(fragment)
if err != nil {
log.Println("Error converting array index to int:", err)
continue
}
datum = datum.([]interface{})[index-1]
default:
datum = datum.(map[string]interface{})[fragment]
}
//fmt.Println(datum)
}
return datum
}