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) // add Decoder and Encoder // use yaml github.com/gookit/config/yaml // AddDriver(Yaml, yaml.Driver) // use toml github.com/gookit/config/toml // AddDriver(Toml, toml.Driver) // use toml github.com/gookit/config/hcl // AddDriver(Hcl, hcl.Driver) // Or // config.DecoderEncoder(config.JSON, yaml.Decoder, yaml.Encoder) 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 interface{}) error
- func Bool(key string, defVal ...bool) bool
- func ClearAll()
- func Data() map[string]interface{}
- func Delimiter(sep byte) func(*Options)
- func DumpTo(out io.Writer, format string) (int64, error)
- func EnableCache(opts *Options)
- func Exists(key string, findByPath ...bool) bool
- func Float(key string, defVal ...float64) float64
- func Get(key string, findByPath ...bool) interface{}
- func GetEnv(name string, defVal ...string) (val string)
- func GetValue(key string, findByPath ...bool) (interface{}, 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 LoadData(dataSource ...interface{}) error
- func LoadExists(sourceFiles ...string) error
- func LoadExistsByFormat(format string, sourceFiles ...string) error
- func LoadFiles(sourceFiles ...string) error
- func LoadFilesByFormat(format string, sourceFiles ...string) error
- func LoadFlags(keys []string) error
- func LoadOSEnv(keys []string, keyToLower bool)
- 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 MapStruct(key string, dst interface{}) error
- func ParseEnv(opts *Options)
- func ParseEnvVarStringHookFunc() mapstructure.DecodeHookFunc
- func Readonly(opts *Options)
- func Set(key string, val interface{}, setByPath ...bool) error
- func SetData(data map[string]interface{})
- func SetDecoder(format string, decoder Decoder)
- func SetEncoder(format string, encoder Encoder)
- func String(key string, defVal ...string) string
- func StringMap(key string) map[string]string
- func Strings(key string) []string
- func Uint(key string, defVal ...uint) uint
- func WithOptions(opts ...func(*Options))
- func WriteTo(out io.Writer) (int64, error)
- type Config
- func (c *Config) AddDriver(driver Driver)
- func (c *Config) BindStruct(key string, dst interface{}) 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]interface{}
- func (c *Config) DelDriver(format string)
- func (c *Config) DumpTo(out io.Writer, format string) (n int64, err error)
- 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) interface{}
- func (c *Config) GetValue(key string, findByPath ...bool) (value interface{}, 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) LoadData(dataSources ...interface{}) (err error)
- func (c *Config) LoadExists(sourceFiles ...string) (err error)
- func (c *Config) LoadExistsByFormat(format string, sourceFiles ...string) (err error)
- func (c *Config) LoadFiles(sourceFiles ...string) (err error)
- func (c *Config) LoadFilesByFormat(format string, sourceFiles ...string) (err error)
- func (c *Config) LoadFlags(keys []string) (err error)
- func (c *Config) LoadOSEnv(keys []string, keyToLower bool)
- 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) MapStruct(key string, dst interface{}) error
- func (c *Config) Name() string
- func (c *Config) Options() *Options
- func (c *Config) Readonly()
- func (c *Config) Set(key string, val interface{}, setByPath ...bool) (err error)
- func (c *Config) SetData(data map[string]interface{})
- func (c *Config) SetDecoder(format string, decoder Decoder)
- func (c *Config) SetDecoders(decoders map[string]Decoder)
- func (c *Config) SetEncoder(format string, encoder Encoder)
- func (c *Config) SetEncoders(encoders map[string]Encoder)
- 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) Structure(key string, dst interface{}) error
- 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) WithOptions(opts ...func(*Options)) *Config
- func (c *Config) WriteTo(out io.Writer) (n int64, err error)
- type Decoder
- type Driver
- type Encoder
- type Options
Examples ¶
Constants ¶
const ( Ini = "ini" Hcl = "hcl" Yml = "yml" JSON = "json" Yaml = "yaml" Toml = "toml" )
There are supported config format
Variables ¶
var JSONAllowComments = true
JSONAllowComments support write comments on json file.
var JSONDriver = &jsonDriver{name: JSON}
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 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
func LoadExistsByFormat ¶ added in v2.0.26
LoadExistsByFormat load one or multi files by give format
func LoadFilesByFormat ¶ added in v2.0.26
LoadFilesByFormat load one or multi files by give format
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 MapStruct ¶
MapStruct alias method of the 'Structure' Usage:
dbInfo := &Db{} config.MapStruct("db", dbInfo)
func ParseEnvVarStringHookFunc ¶ added in v2.0.25
func ParseEnvVarStringHookFunc() mapstructure.DecodeHookFunc
ParseEnvVarStringHookFunc returns a DecodeHookFunc that parse ENV var
func SetData ¶ added in v2.0.16
func SetData(data map[string]interface{})
SetData for override the Config.Data
func SetDecoder ¶
SetDecoder add/set a format decoder Deprecated please use driver instead
func SetEncoder ¶
SetEncoder set a encoder for the format Deprecated please use driver instead
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) LoadData ¶
LoadData load data from map OR struct The dataSources can be:
- map[string]interface{}
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
func (*Config) LoadFilesByFormat ¶ added in v2.0.26
LoadFilesByFormat load one or multi files by give format
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) 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.Yml, []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) Readonly ¶
func (c *Config) Readonly()
Readonly disable set data to config. Usage:
config.LoadFiles(a, b, c) config.Readonly()
func (*Config) SetDecoder ¶
SetDecoder set decoder Deprecated please use driver instead
func (*Config) SetDecoders ¶
SetDecoders set decoders Deprecated please use driver instead
func (*Config) SetEncoder ¶
SetEncoder set a encoder for the format Deprecated please use driver instead
func (*Config) SetEncoders ¶
SetEncoders set encoders Deprecated please use driver instead
func (*Config) Structure ¶
Structure get config data and binding to the dst structure. Usage:
dbInfo := Db{} config.Structure("db", &dbInfo)
func (*Config) WithOptions ¶
WithOptions apply some options
type 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 // Deprecated // please set tag name by DecoderConfig 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 // DecoderConfig setting for binding data to struct DecoderConfig *mapstructure.DecoderConfig }
Options config options
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 dotnev provide load .env data to os ENV
|
Package dotnev provide load .env data to os ENV |
Package hcl is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl
|
Package hcl is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl |
Package hcl2 is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl docs for HCL v2 https://pkg.go.dev/github.com/hashicorp/hcl/v2
|
Package hcl2 is driver use HCL format content as config source about HCL, please see https://github.com/hashicorp/hcl docs for HCL v2 https://pkg.go.dev/github.com/hashicorp/hcl/v2 |
Package ini is driver use INI format content as config source about ini parse, please see https://github.com/gookit/ini/parser
|
Package ini is driver use INI format content as config source about ini parse, please see https://github.com/gookit/ini/parser |
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 toml is driver use TOML format content as config source Usage please see example:
|
Package toml is driver use TOML format content as config source Usage please see example: |
Package yaml is a driver use YAML format content as config source Usage please see example:
|
Package yaml is a driver use YAML format content as config source Usage please see example: |
Package yaml is a driver use YAML format content as config source Usage please see example:
|
Package yaml is a driver use YAML format content as config source Usage please see example: |