-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
117 lines (94 loc) · 1.86 KB
/
config.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
106
107
108
109
110
111
112
113
114
115
116
117
// Copyright 2014 The zhgo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package config
import (
"encoding/json"
"errors"
"io/ioutil"
"strings"
)
type Config struct {
// Original configuration string
str string
// The replacement value
re map[string]string
}
// Load configuration file
func (c *Config) Load(p string) error {
b, err := ioutil.ReadFile(p)
if err != nil {
return err
}
c.str = string(b)
return nil
}
// Read from string
func (c *Config) Read(str string) error {
if str == "" {
return errors.New("Configuration body is empty")
}
c.str = str
return nil
}
// Configuration parsing
func (c *Config) Parse(j interface{}) error {
type variables struct {
Variables map[string]string
}
r1 := variables{Variables: map[string]string{}}
// Parsing variables node
var c1 Config
c1.Read(c.str)
err := c1.parse(&r1)
if err != nil {
return err
}
// Merge
for k, v := range r1.Variables {
c.re[k] = v
}
err = c.parse(j)
if err != nil {
return err
}
return nil
}
func (c *Config) Replace(r map[string]string) *Config {
if r == nil {
c.re = make(map[string]string)
} else {
c.re = r
}
return c
}
// Configuration parsing
func (c *Config) parse(j interface{}) error {
if c.str == "" {
return errors.New("Configuration body is empty")
}
c.replace()
//decode string(JSON format)
dec := json.NewDecoder(strings.NewReader(c.str))
err := dec.Decode(j)
if err != nil {
return err
}
return nil
}
//Replace placeholer({})
func (c *Config) replace() {
if len(c.re) == 0 {
return
}
for k, v := range c.re {
//c.str = regexp.MustCompile(k).ReplaceAllLiteralString(c.str, v)
c.str = strings.Replace(c.str, k, v, -1)
}
}
// New Config
func NewConfig(p string) *Config {
c := Config{re: make(map[string]string)}
c.Load(p)
return &c
}