/
config.go
422 lines (348 loc) · 8.76 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*
Package config is a go config management implement. support YAML,TOML,JSON,INI,HCL format.
Source code and other details for the project are available at GitHub:
https://github.com/gookit/config
JSON format content example:
{
"name": "app",
"debug": false,
"baseKey": "value",
"age": 123,
"envKey": "${SHELL}",
"envKey1": "${NotExist|defValue}",
"map1": {
"key": "val",
"key1": "val1",
"key2": "val2"
},
"arr1": [
"val",
"val1",
"val2"
],
"lang": {
"dir": "res/lang",
"defLang": "en",
"allowed": {
"en": "val",
"zh-CN": "val2"
}
}
}
Usage please see example(more example please see examples folder in the lib):
*/
package config
import (
"fmt"
"os"
"strings"
"sync"
)
// There are supported config format
const (
Ini = "ini"
Hcl = "hcl"
Yml = "yml"
JSON = "json"
Yaml = "yaml"
Toml = "toml"
// default delimiter
defaultDelimiter byte = '.'
// default struct tag name for binding data to struct
defaultStructTag = "mapstructure"
)
// internal vars
type intArr []int
type strArr []string
type intMap map[string]int
type strMap map[string]string
// type fmtName string
// This is a default config manager instance
var dc = New("default")
// Driver interface
type Driver interface {
Name() string
GetDecoder() Decoder
GetEncoder() Encoder
}
// Decoder for decode yml,json,toml format content
type Decoder func(blob []byte, v interface{}) (err error)
// Encoder for decode yml,json,toml format content
type Encoder func(v interface{}) (out []byte, err error)
// Options config options
type Options struct {
// parse env value. like: "${EnvName}" "${EnvName|default}"
ParseEnv bool
// config is readonly
Readonly bool
// enable config data cache
EnableCache bool
// parse key, allow find value by key path. eg: 'key.sub' will find `map[key]sub`
ParseKey bool
// tag name for binding data to struct
TagName string
// the delimiter char for split key path, if `FindByPath=true`. default is '.'
Delimiter byte
// default write format
DumpFormat string
// default input format
ReadFormat string
}
// Config structure definition
type Config struct {
err error
// config instance name
name string
lock sync.RWMutex
// config options
opts *Options
// all config data
data map[string]interface{}
// loaded config files records
loadedFiles []string
loadedDriver []string
// decoders["toml"] = func(blob []byte, v interface{}) (err error){}
// decoders["yaml"] = func(blob []byte, v interface{}) (err error){}
// drivers map[string]Driver TODO Deprecated decoder and encoder, use driver instead
decoders map[string]Decoder
encoders map[string]Encoder
// cache got config data
intCache map[string]int
strCache map[string]string
iArrCache map[string]intArr
iMapCache map[string]intMap
sArrCache map[string]strArr
sMapCache map[string]strMap
}
// New config instance
func New(name string) *Config {
return &Config{
name: name,
opts: newDefaultOption(),
data: make(map[string]interface{}),
// default add JSON driver
encoders: map[string]Encoder{JSON: JSONEncoder},
decoders: map[string]Decoder{JSON: JSONDecoder},
}
}
// NewEmpty config instance
func NewEmpty(name string) *Config {
return &Config{
name: name,
opts: newDefaultOption(),
data: make(map[string]interface{}),
// don't add any drivers
encoders: map[string]Encoder{},
decoders: map[string]Decoder{},
}
}
// NewWithOptions config instance
func NewWithOptions(name string, opts ...func(*Options)) *Config {
c := New(name)
c.WithOptions(opts...)
return c
}
// Default get the default instance
func Default() *Config {
return dc
}
func newDefaultOption() *Options {
return &Options{
ParseKey: true,
TagName: defaultStructTag,
Delimiter: defaultDelimiter,
DumpFormat: JSON,
ReadFormat: JSON,
}
}
/*************************************************************
* config setting
*************************************************************/
// ParseEnv set parse env
func ParseEnv(opts *Options) {
opts.ParseEnv = true
}
// Readonly set readonly
func Readonly(opts *Options) {
opts.Readonly = true
}
// Delimiter set delimiter char
func Delimiter(sep byte) func(*Options) {
return func(opts *Options) {
opts.Delimiter = sep
}
}
// EnableCache set readonly
func EnableCache(opts *Options) {
opts.EnableCache = true
}
// WithOptions with options
func WithOptions(opts ...func(*Options)) { dc.WithOptions(opts...) }
// WithOptions apply some options
func (c *Config) WithOptions(opts ...func(*Options)) {
if !c.IsEmpty() {
panic("config: Cannot set options after data has been loaded")
}
// apply options
for _, opt := range opts {
opt(c.opts)
}
}
// GetOptions get options
func GetOptions() *Options { return dc.Options() }
// Options get
func (c *Config) Options() *Options {
return c.opts
}
// Readonly disable set data to config.
// Usage:
// config.LoadFiles(a, b, c)
// config.Readonly()
func (c *Config) Readonly() {
c.opts.Readonly = true
}
/*************************************************************
* config drivers
*************************************************************/
// AddDriver set a decoder and encoder driver for a format.
func AddDriver(driver Driver) { dc.AddDriver(driver) }
// AddDriver set a decoder and encoder driver for a format.
func (c *Config) AddDriver(driver Driver) {
format := driver.Name()
c.decoders[format] = driver.GetDecoder()
c.encoders[format] = driver.GetEncoder()
}
// HasDecoder has decoder
func (c *Config) HasDecoder(format string) bool {
format = fixFormat(format)
_, ok := c.decoders[format]
return ok
}
// SetDecoder add/set a format decoder
func SetDecoder(format string, decoder Decoder) {
dc.SetDecoder(format, decoder)
}
// SetDecoder set decoder
func (c *Config) SetDecoder(format string, decoder Decoder) {
format = fixFormat(format)
c.decoders[format] = decoder
}
// SetDecoders set decoders
func (c *Config) SetDecoders(decoders map[string]Decoder) {
for format, decoder := range decoders {
c.SetDecoder(format, decoder)
}
}
// SetEncoder set a encoder for the format
func SetEncoder(format string, encoder Encoder) {
dc.SetEncoder(format, encoder)
}
// SetEncoder set a encoder for the format
func (c *Config) SetEncoder(format string, encoder Encoder) {
format = fixFormat(format)
c.encoders[format] = encoder
}
// SetEncoders set encoders
func (c *Config) SetEncoders(encoders map[string]Encoder) {
for format, encoder := range encoders {
c.SetEncoder(format, encoder)
}
}
// HasEncoder has encoder
func (c *Config) HasEncoder(format string) bool {
format = fixFormat(format)
_, ok := c.encoders[format]
return ok
}
// DelDriver delete driver of the format
func (c *Config) DelDriver(format string) {
format = fixFormat(format)
if _, ok := c.decoders[format]; ok {
delete(c.decoders, format)
}
if _, ok := c.encoders[format]; ok {
delete(c.encoders, format)
}
}
/*************************************************************
* helper methods
*************************************************************/
// Name get config name
func (c *Config) Name() string {
return c.name
}
// Error get last error
func (c *Config) Error() error {
return c.err
}
// IsEmpty of the config
func (c *Config) IsEmpty() bool {
return len(c.data) == 0
}
// LoadedFiles get loaded files name
func (c *Config) LoadedFiles() []string {
return c.loadedFiles
}
// ClearAll data and caches
func ClearAll() { dc.ClearAll() }
// ClearAll data and caches
func (c *Config) ClearAll() {
c.ClearData()
c.ClearCaches()
c.loadedFiles = []string{}
c.opts.Readonly = false
}
// ClearData clear data
func (c *Config) ClearData() {
c.data = make(map[string]interface{})
c.loadedFiles = []string{}
}
// ClearCaches clear caches
func (c *Config) ClearCaches() {
if c.opts.EnableCache {
c.intCache = nil
c.strCache = nil
c.sMapCache = nil
c.sArrCache = nil
}
}
/*************************************************************
* helper methods/functions
*************************************************************/
// record error
func (c *Config) addError(err error) {
c.err = err
}
// format and record error
func (c *Config) addErrorf(format string, a ...interface{}) {
c.err = fmt.Errorf(format, a...)
}
// GetEnv get os ENV value by name
// Deprecated
// please use Getenv() instead
func GetEnv(name string, defVal ...string) (val string) {
return Getenv(name, defVal...)
}
// Getenv get os ENV value by name. like os.Getenv, but support default value
// Notice:
// - Key is not case sensitive when getting
func Getenv(name string, defVal ...string) (val string) {
if val = os.Getenv(name); val != "" {
return
}
if len(defVal) > 0 {
val = defVal[0]
}
return
}
// format key
func formatKey(key, sep string) string {
return strings.Trim(strings.TrimSpace(key), sep)
}
// fix yaml format
func fixFormat(f string) string {
if f == Yml {
f = Yaml
}
return f
}