Documentation ¶
Overview ¶
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):
Example ¶
// WithOptions(ParseEnv) // use yaml github.com/gookit/config/yamlv3 // AddDriver(Yaml, yamlv3.Driver) // use toml github.com/gookit/config/toml // AddDriver(Toml, toml.Driver) // use toml github.com/gookit/config/hcl // AddDriver(Hcl, hcl.Driver) err := LoadFiles("testdata/json_base.json") if err != nil { panic(err) } // fmt.Printf("config data: \n %#v\n", Data()) err = LoadFiles("testdata/json_other.json") // LoadFiles("testdata/json_base.json", "testdata/json_other.json") if err != nil { panic(err) } // load from string err = LoadSources(JSON, []byte(jsonStr)) if err != nil { panic(err) } // fmt.Printf("config data: \n %#v\n", Data()) fmt.Print("get config example:\n") name := String("name") fmt.Printf("- get string\n val: %v\n", name) arr1 := Strings("arr1") fmt.Printf("- get array\n val: %#v\n", arr1) val0 := String("arr1.0") fmt.Printf("- get sub-value by path 'arr.index'\n val: %#v\n", val0) map1 := StringMap("map1") fmt.Printf("- get map\n val: %#v\n", map1) val0 = String("map1.key") fmt.Printf("- get sub-value by path 'map.key'\n val: %#v\n", val0) // can parse env name(ParseEnv: true) fmt.Printf("get env 'envKey' val: %s\n", String("envKey", "")) fmt.Printf("get env 'envKey1' val: %s\n", String("envKey1", "")) // set value _ = Set("name", "new name") name = String("name") fmt.Printf("- set string\n val: %v\n", name) // if you want export config data // buf := new(bytes.Buffer) // _, err = config.DumpTo(buf, config.JSON) // if err != nil { // panic(err) // } // fmt.Printf("export config:\n%s", buf.String()) // Out: // get config example: // - get string // val: app // - get array // val: []string{"val", "val1", "val2"} // - get sub-value by path 'arr.index' // val: "val" // - get map // val: map[string]string{"key":"val", "key1":"val1", "key2":"val2"} // - get sub-value by path 'map.key' // val: "val" // get env 'envKey' val: /bin/zsh // get env 'envKey1' val: defValue // - set string // val: new name
Output:
Example (ExportConfig) ¶
// Notice: before dump please set driver encoder // SetEncoder(Yaml, yaml.Encoder) ClearAll() // load from string err := LoadStrings(JSON, `{ "name": "app", "age": 34 }`) if err != nil { panic(err) } buf := new(bytes.Buffer) _, err = DumpTo(buf, JSON) if err != nil { panic(err) } fmt.Printf("%s", buf.String())
Output: {"age":34,"name":"app"}
Index ¶
- Constants
- Variables
- func AddDriver(driver Driver)
- func BindStruct(key string, dst any) error
- func Bool(key string, defVal ...bool) bool
- func ClearAll()
- func Data() map[string]any
- func Decode(dst any) error
- func Delimiter(sep byte) func(*Options)
- func DumpTo(out io.Writer, format string) (int64, error)
- func Duration(key string, defVal ...time.Duration) time.Duration
- func EnableCache(opts *Options)
- func Exists(key string, findByPath ...bool) bool
- func Float(key string, defVal ...float64) float64
- func Get(key string, findByPath ...bool) any
- func GetEnv(name string, defVal ...string) (val string)
- func GetValue(key string, findByPath ...bool) (any, bool)
- func Getenv(name string, defVal ...string) (val string)
- func Int(key string, defVal ...int) int
- func Int64(key string, defVal ...int64) int64
- func IntMap(key string) map[string]int
- func Ints(key string) []int
- func Keys() []string
- func LoadData(dataSource ...any) error
- func LoadExists(sourceFiles ...string) error
- func LoadExistsByFormat(format string, configFiles ...string) error
- func LoadFiles(sourceFiles ...string) error
- func LoadFilesByFormat(format string, configFiles ...string) error
- func LoadFlags(keys []string) error
- func LoadFromDir(dirPath, format string) error
- func LoadOSEnv(keys []string, keyToLower bool)deprecated
- func LoadOSEnvs(nameToKeyMap map[string]string)
- func LoadRemote(format, url string) error
- func LoadSources(format string, src []byte, more ...[]byte) error
- func LoadStrings(format string, str string, more ...string) error
- func MapOnExists(key string, dst any) error
- func MapStruct(key string, dst any) error
- func MustString(key string) string
- func ParseDefault(opts *Options)
- func ParseEnv(opts *Options)
- func ParseTime(opts *Options)
- func Readonly(opts *Options)
- func ReloadFiles() error
- func Reset()
- func SaveFileOnSet(fileName string, format string) func(options *Options)
- func Set(key string, val any, setByPath ...bool) error
- func SetData(data map[string]any)
- func SetDecoder(format string, decoder Decoder)deprecated
- func SetEncoder(format string, encoder Encoder)deprecated
- func String(key string, defVal ...string) string
- func StringMap(key string) map[string]string
- func Strings(key string) []string
- func StringsBySplit(key, sep string) []string
- func SubDataMap(key string) maputil.Map
- func Uint(key string, defVal ...uint) uint
- func ValDecodeHookFunc(parseEnv, parseTime bool) mapstructure.DecodeHookFunc
- func WithDriver(drivers ...Driver)
- func WithHookFunc(fn HookFunc) func(*Options)
- func WithOptions(opts ...func(*Options))
- func WithTagName(tagName string) func(*Options)
- func WriteTo(out io.Writer) (int64, error)
- type Config
- func (c *Config) AddDriver(driver Driver)
- func (c *Config) BindStruct(key string, dst any) error
- func (c *Config) Bool(key string, defVal ...bool) (value bool)
- func (c *Config) ClearAll()
- func (c *Config) ClearCaches()
- func (c *Config) ClearData()
- func (c *Config) Data() map[string]any
- func (c *Config) Decode(dst any) error
- func (c *Config) DelDriver(format string)
- func (c *Config) DriverNames() []string
- func (c *Config) DumpTo(out io.Writer, format string) (n int64, err error)
- func (c *Config) DumpToFile(fileName string, format string) (err error)
- func (c *Config) Duration(key string, defVal ...time.Duration) time.Duration
- func (c *Config) Error() error
- func (c *Config) Exists(key string, findByPath ...bool) (ok bool)
- func (c *Config) Float(key string, defVal ...float64) (value float64)
- func (c *Config) Get(key string, findByPath ...bool) any
- func (c *Config) GetValue(key string, findByPath ...bool) (value any, ok bool)
- func (c *Config) HasDecoder(format string) bool
- func (c *Config) HasEncoder(format string) bool
- func (c *Config) Int(key string, defVal ...int) (value int)
- func (c *Config) Int64(key string, defVal ...int64) (value int64)
- func (c *Config) IntMap(key string) (mp map[string]int)
- func (c *Config) Ints(key string) (arr []int)
- func (c *Config) IsEmpty() bool
- func (c *Config) Keys() []string
- func (c *Config) LoadData(dataSources ...any) (err error)
- func (c *Config) LoadExists(sourceFiles ...string) (err error)
- func (c *Config) LoadExistsByFormat(format string, configFiles ...string) (err error)
- func (c *Config) LoadFiles(sourceFiles ...string) (err error)
- func (c *Config) LoadFilesByFormat(format string, configFiles ...string) (err error)
- func (c *Config) LoadFlags(keys []string) (err error)
- func (c *Config) LoadFromDir(dirPath, format string) (err error)
- func (c *Config) LoadOSEnv(keys []string, keyToLower bool)deprecated
- func (c *Config) LoadOSEnvs(nameToKeyMap map[string]string)
- func (c *Config) LoadRemote(format, url string) (err error)
- func (c *Config) LoadSources(format string, src []byte, more ...[]byte) (err error)
- func (c *Config) LoadStrings(format string, str string, more ...string) (err error)
- func (c *Config) LoadedFiles() []string
- func (c *Config) LoadedUrls() []string
- func (c *Config) MapOnExists(key string, dst any) error
- func (c *Config) MapStruct(key string, dst any) error
- func (c *Config) MustString(key string) string
- func (c *Config) Name() string
- func (c *Config) Options() *Options
- func (c *Config) Readonly()
- func (c *Config) ReloadFiles() (err error)
- func (c *Config) Set(key string, val any, setByPath ...bool) (err error)
- func (c *Config) SetData(data map[string]any)
- func (c *Config) SetDecoder(format string, decoder Decoder)deprecated
- func (c *Config) SetDecoders(decoders map[string]Decoder)deprecated
- func (c *Config) SetEncoder(format string, encoder Encoder)deprecated
- func (c *Config) SetEncoders(encoders map[string]Encoder)deprecated
- func (c *Config) String(key string, defVal ...string) string
- func (c *Config) StringMap(key string) (mp map[string]string)
- func (c *Config) Strings(key string) (arr []string)
- func (c *Config) StringsBySplit(key, sep string) (ss []string)
- func (c *Config) Structure(key string, dst any) error
- func (c *Config) SubDataMap(key string) maputil.Map
- func (c *Config) ToJSON() string
- func (c *Config) Uint(key string, defVal ...uint) (value uint)
- func (c *Config) With(fn func(c *Config)) *Config
- func (c *Config) WithDriver(drivers ...Driver) *Config
- func (c *Config) WithOptions(opts ...func(opts *Options)) *Config
- func (c *Config) WriteTo(out io.Writer) (n int64, err error)
- type Decoder
- type Driver
- type Encoder
- type HookFunc
- type Options
- type StdDriver
Examples ¶
Constants ¶
const ( Ini = "ini" Hcl = "hcl" Yml = "yml" JSON = "json" Yaml = "yaml" Toml = "toml" Prop = "properties" )
There are supported config format
const ( OnSetValue = "set.value" OnSetData = "set.data" OnLoadData = "load.data" OnReloadData = "reload.data" OnCleanData = "clean.data" )
there are some event names for config data changed.
Variables ¶
var ( // JSONAllowComments support write comments on json file. JSONAllowComments = true // JSONMarshalIndent if not empty, will use json.MarshalIndent for encode data. // // Deprecated: please use JSONDriver.MarshalIndent JSONMarshalIndent string )
var ( ErrReadonly = errors.New("the config instance in 'readonly' mode") ErrKeyIsEmpty = errors.New("the config key is cannot be empty") ErrNotFound = errors.New("this key does not exist in the config") )
some common errors definitions
var JSONDriver = &jsonDriver{ driverName: JSON, ClearComments: JSONAllowComments, MarshalIndent: JSONMarshalIndent, }
JSONDriver instance fot json
Functions ¶
func AddDriver ¶
func AddDriver(driver Driver)
AddDriver set a decoder and encoder driver for a format.
func BindStruct ¶ added in v2.0.11
BindStruct alias method of the 'Structure'
func Decode ¶ added in v2.1.4
Decode all config data to the dst ptr
Usage:
myConf := &MyConf{} config.Decode(myConf)
func Duration ¶ added in v2.1.8
Duration get a time.Duration type value. if not found return default value
func Get ¶
Get config value by key string, support get sub-value by key path(eg. 'map.key'),
- ok is true, find value from config
- ok is false, not found or error
func Getenv ¶ added in v2.0.10
Getenv get os ENV value by name. like os.Getenv, but support default value
Notice: - Key is not case-sensitive when getting
func LoadExists ¶
LoadExists load one or multi files, will ignore not exist
Usage:
config.LoadExists(file1, file2, ...)
func LoadExistsByFormat ¶ added in v2.0.26
LoadExistsByFormat load one or multi files by give format, will fire OnLoadData event
func LoadFiles ¶
LoadFiles load one or multi files, will fire OnLoadData event
Usage:
config.LoadFiles(file1, file2, ...)
func LoadFilesByFormat ¶ added in v2.0.26
LoadFilesByFormat load one or multi config files by give format, will fire OnLoadData event
func LoadFromDir ¶ added in v2.1.8
LoadFromDir Load custom format files from the given directory, the file name will be used as the key.
Example:
// file: /somedir/task.json LoadFromDir("/somedir", "json") // after load Config.data = map[string]any{"task": file data}
func LoadOSEnvs ¶ added in v2.1.7
LoadOSEnvs load data from OS ENVs. format: {ENV_NAME: config_key}
func LoadRemote ¶
LoadRemote load config data from remote URL.
func LoadSources ¶
LoadSources load one or multi byte data
func LoadStrings ¶
LoadStrings load one or multi string
func MapOnExists ¶ added in v2.1.0
MapOnExists mapping data to the dst structure only on key exists.
func MapStruct ¶
MapStruct alias method of the 'Structure'
Usage:
dbInfo := &Db{} config.MapStruct("db", dbInfo)
func MustString ¶ added in v2.2.0
MustString get a string by key, will panic on empty or not exists
func ParseDefault ¶ added in v2.1.4
func ParseDefault(opts *Options)
ParseDefault tag value on binding data to struct.
func ReloadFiles ¶ added in v2.1.7
func ReloadFiles() error
ReloadFiles reload config data use loaded files
func SaveFileOnSet ¶ added in v2.1.3
SaveFileOnSet set hook func
func SetDecoder
deprecated
func SetEncoder
deprecated
func StringsBySplit ¶ added in v2.2.0
StringsBySplit get []string by split a string value.
func SubDataMap ¶ added in v2.1.8
SubDataMap get sub config data as maputil.Map
func ValDecodeHookFunc ¶ added in v2.1.3
func ValDecodeHookFunc(parseEnv, parseTime bool) mapstructure.DecodeHookFunc
ValDecodeHookFunc returns a mapstructure.DecodeHookFunc that parse ENV var, and more custom parse
func WithDriver ¶ added in v2.1.5
func WithDriver(drivers ...Driver)
WithDriver set multi drivers at once.
func WithHookFunc ¶ added in v2.1.0
WithHookFunc set hook func
func WithTagName ¶ added in v2.1.5
WithTagName set tag name for export to struct
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config structure definition
func NewWithOptions ¶
NewWithOptions config instance
func (*Config) BindStruct ¶ added in v2.0.11
BindStruct alias method of the 'Structure'
func (*Config) Bool ¶
Bool looks up a value for a key in this section and attempts to parse that value as a boolean, along with a boolean result similar to a map lookup.
of following(case insensitive):
- true
- yes
- false
- no
- 1
- 0
The `ok` boolean will be false in the event that the value could not be parsed as a bool
func (*Config) Decode ¶ added in v2.1.4
Decode all config data to the dst ptr.
It's equals:
c.Structure("", dst)
func (*Config) DriverNames ¶ added in v2.1.1
DriverNames get loaded driver names
func (*Config) DumpToFile ¶ added in v2.1.3
DumpToFile use the format(json,yaml,toml) dump config data to a writer
func (*Config) Duration ¶ added in v2.1.8
Duration get a time.Duration type value. if not found return default value
func (*Config) LoadData ¶
LoadData load data from map OR struct
The dataSources can be:
- map[string]any
func (*Config) LoadExists ¶
LoadExists load and parse config files, but will ignore not exists file.
func (*Config) LoadExistsByFormat ¶ added in v2.0.26
LoadExistsByFormat load one or multi files by give format, will fire OnLoadData event
func (*Config) LoadFilesByFormat ¶ added in v2.0.26
LoadFilesByFormat load one or multi files by give format, will fire OnLoadData event
func (*Config) LoadFlags ¶
LoadFlags parse command line arguments, based on provide keys.
Usage:
// 'debug' flag is bool type c.LoadFlags([]string{"env", "debug:bool"})
func (*Config) LoadFromDir ¶ added in v2.1.8
LoadFromDir Load custom format files from the given directory, the file name will be used as the key.
Example:
// file: /somedir/task.json Config.LoadFromDir("/somedir", "json") // after load Config.data = map[string]any{"task": file data}
func (*Config) LoadOSEnvs ¶ added in v2.1.7
LoadOSEnvs load data from os ENVs. format: {ENV_NAME: config_key}
func (*Config) LoadRemote ¶
LoadRemote load config data from remote URL.
Usage:
c.LoadRemote(config.JSON, "http://abc.com/api-config.json")
func (*Config) LoadSources ¶
LoadSources load data from byte content.
Usage:
config.LoadSources(config.Yaml, []byte(` name: blog arr: key: val
`))
func (*Config) LoadStrings ¶
LoadStrings load data from source string content.
func (*Config) LoadedFiles ¶
LoadedFiles get loaded files name
func (*Config) LoadedUrls ¶ added in v2.1.7
LoadedUrls get loaded urls list
func (*Config) MapOnExists ¶ added in v2.1.0
MapOnExists mapping data to the dst structure only on key exists.
- Support ParseEnv on mapping
- Support ParseDefault on mapping
func (*Config) MustString ¶ added in v2.2.0
MustString get a string by key, will panic on empty or not exists
func (*Config) Readonly ¶
func (c *Config) Readonly()
Readonly disable set data to config.
Usage:
config.LoadFiles(a, b, c) config.Readonly()
func (*Config) ReloadFiles ¶ added in v2.1.7
ReloadFiles reload config data use loaded files. use on watching loaded files change
func (*Config) SetDecoder
deprecated
func (*Config) SetDecoders
deprecated
func (*Config) SetEncoder
deprecated
func (*Config) SetEncoders
deprecated
func (*Config) StringsBySplit ¶ added in v2.2.0
StringsBySplit get []string by split a string value.
func (*Config) Structure ¶
Structure get config data and binding to the dst structure.
- Support ParseEnv on mapping
- Support ParseDefault on mapping
Usage:
dbInfo := Db{} config.Structure("db", &dbInfo)
func (*Config) SubDataMap ¶ added in v2.1.8
SubDataMap get sub config data as maputil.Map
TIP: will not enable parse Env and more
func (*Config) WithDriver ¶ added in v2.1.5
WithDriver set multi drivers at once.
func (*Config) WithOptions ¶
WithOptions apply some options
type Decoder ¶
Decoder for decode yml,json,toml format content
var JSONDecoder Decoder = func(data []byte, v any) (err error) { JSONDriver.ClearComments = JSONAllowComments return JSONDriver.Decode(data, v) }
JSONDecoder for json decode
type Driver ¶
Driver interface. TODO refactor: rename GetDecoder() to Decode(), rename GetEncoder() to Encode()
type Encoder ¶
Encoder for decode yml,json,toml format content
var JSONEncoder Encoder = func(v any) (out []byte, err error) { JSONDriver.MarshalIndent = JSONMarshalIndent return JSONDriver.Encode(v) }
JSONEncoder for json encode
type Options ¶
type Options struct { // ParseEnv parse env value. like: "${EnvName}" "${EnvName|default}" ParseEnv bool // ParseTime parses a duration string to time.Duration // eg: 10s, 2m ParseTime bool // Readonly config is readonly Readonly bool // EnableCache enable config data cache EnableCache bool // ParseKey parse key path, allow find value by key path. eg: 'key.sub' will find `map[key]sub` ParseKey bool // TagName tag name for binding data to struct // // Tips: please set tag name by DecoderConfig TagName string // Delimiter the delimiter char for split key path, if `FindByPath=true`. default is '.' Delimiter byte // DumpFormat default write format DumpFormat string // ReadFormat default input format ReadFormat string // DecoderConfig setting for binding data to struct. such as: TagName DecoderConfig *mapstructure.DecoderConfig // HookFunc on data changed. you can do something... HookFunc HookFunc // ParseDefault tag on binding data to struct. tag: default ParseDefault bool }
Options config options
type StdDriver ¶ added in v2.1.1
type StdDriver struct {
// contains filtered or unexported fields
}
StdDriver struct
func (*StdDriver) GetDecoder ¶ added in v2.1.1
GetDecoder of driver
func (*StdDriver) GetEncoder ¶ added in v2.1.1
GetEncoder of driver
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
These are some sample code for YAML,TOML,JSON,INI,HCL
|
These are some sample code for YAML,TOML,JSON,INI,HCL |
Package hcl is driver use HCL format content as config source
|
Package hcl is driver use HCL format content as config source |
Package hclv2 is driver use HCL format content as config source
|
Package hclv2 is driver use HCL format content as config source |
Package ini is driver use INI format content as config source
|
Package ini is driver use INI format content as config source |
Package json use the https://github.com/json-iterator/go for parse json
|
Package json use the https://github.com/json-iterator/go for parse json |
Package json5 use the https://github.com/yosuke-furukawa/json5 for parse json5
|
Package json5 use the https://github.com/yosuke-furukawa/json5 for parse json5 |
Package other is an example of a custom driver
|
Package other is an example of a custom driver |
Package properties is a driver use Java properties format content as config source
|
Package properties is a driver use Java properties format content as config source |
Package toml is driver use TOML format content as config source
|
Package toml is driver use TOML format content as config source |
Package yaml is a driver use YAML format content as config source
|
Package yaml is a driver use YAML format content as config source |
Package yamlv3 is a driver use YAML format content as config source
|
Package yamlv3 is a driver use YAML format content as config source |