-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfigo.go
141 lines (114 loc) · 2.2 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
137
138
139
140
141
package configo
import (
"os"
"runtime"
"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)
}
}
//GetSystemSeparator System Separator
func GetSystemSeparator() string {
if runtime.GOOS == "windows" {
return "\\"
}
return "/"
}
//NewDefaultConfig default config
func NewDefaultConfig() *Config {
wd, err := os.Getwd()
fp := ""
if err == nil {
fp = strings.Join([]string{wd, DEFAULT_CONFIG_FILE}, GetSystemSeparator())
}
return NewConfig(fp)
}
//NewConfig new config
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
}
//Load default load
func Load() error {
return config.Load()
}
//Load load
func (c *Config) Load() error {
file, openErr := os.Open(c.Path)
if openErr != nil {
return ErrorConfigCannotOpen
}
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
}
//Get default get
func Get(s string) (*Property, error) {
return config.Get(s)
}
//Get config get
func (c *Config) Get(s string) (*Property, error) {
if config.Type == TYPE_DEFAULT {
p := envDefaultGet(s)
if p != nil {
return p, nil
}
return nil, ErrorConfigGetProperty
}
return nil, ErrorConfigGetPropertyType
}
//Get property get
func (p *Property) Get(s string) (string, error) {
if v, ok := (*p)[s]; ok {
return v, nil
}
return "", ErrorConfigGetPropertyValue
}
//MustGet property get with default value
func (p *Property) MustGet(s, d string) string {
if v, ok := (*p)[s]; ok {
return v
}
return d
}