forked from godcong/configo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configo.go
136 lines (107 loc) · 2.07 KB
/
configo.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package configo
import (
"os"
"strings"
)
type CONFIG_TYPE int
const (
TYPE_DEFAULT CONFIG_TYPE = iota
)
const (
PROCESS_NONE = iota
PROCESS_COMMON
PROCESS_PROPERTY
)
type (
Common interface{}
Property map[string]string
Default map[string]Property
)
type Config struct {
Type CONFIG_TYPE
Path string
Configure Common
}
var config *Config
const DEFAULT_CONFIG_FILE = "config.env"
func init() {
config = NewDefaultConfig()
if e := config.Load(); e != nil {
config.Configure = make(Default)
}
}
func GetSystemSeparator() string {
return SYSTEM_SEPARATOR
}
func NewDefaultConfig() *Config {
wd, err := os.Getwd()
fp := ""
if err == nil {
fp = strings.Join([]string{wd, DEFAULT_CONFIG_FILE}, GetSystemSeparator())
}
return NewConfig(fp)
}
func NewConfig(path string, args ...CONFIG_TYPE) *Config {
defaultConfig := make(Default)
configType := TYPE_DEFAULT
if args != nil {
configType = args[0]
}
conf := &Config{
Type: configType,
Path: path,
Configure: (Common)(defaultConfig),
}
return conf
}
func (c *Config) Properties() *Common {
c.Load()
return &c.Configure
}
func Load() error {
return config.Load()
}
func (c *Config) Load() error {
file, openErr := os.Open(c.Path)
if openErr != nil {
return ERROR_CONFIG_CANNOT_OPEN
}
defer file.Close()
if e := envLoad(c, file); e != nil {
return e
}
return nil
}
func envLoad(c *Config, f *os.File) error {
if c.Type == TYPE_DEFAULT {
return envDefault(c, f)
}
return nil
}
func Get(s string) (*Property, error) {
return config.Get(s)
}
func (c *Config) Get(s string) (*Property, error) {
if config.Type == TYPE_DEFAULT {
if v, ok := c.Configure.(Default); ok {
p := envDefaultGet(v, s)
if p != nil {
return p, nil
}
}
return nil, ERROR_CONFIG_GET_PROPERTY
}
return nil, ERROR_CONFIG_GET_PROPERTY_TYPE
}
func (p *Property) Get(s string) (string, error) {
if v, ok := (*p)[s]; ok {
return v, nil
}
return "", ERROR_CONFIG_GET_PROPERTY_VALUE
}
func (p *Property) MustGet(s, d string) string {
if v, ok := (*p)[s]; ok {
return v
}
return d
}