go-ucfg
ucfg - Universal Configuration
ucfg is a Golang library to handle hjson, json, and yaml configuration files in your Golang project. It was developed for the libbeat framework and used by all beats.
Dot notations
ufcg allows you to load yaml configuration files using dots instead of indentation. For example instead of having:
config:
user: name
with ucfg you can write:
config.user: name
实践
$ go get github.com/elastic/go-ucfg
package main import ( "fmt" "os" "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" ) type person struct { Age int `config:"age"` } type ExampleConfig struct { Counter int `config:"counter" validate:"min=0, max=9"` Person person `config:"config"` } // Defines default config option var ( defaultConfig = ExampleConfig{ Counter: 8, Person: person{ Age: 8, }, } ) func main() { appConfig := defaultConfig // copy default config so it's not overwritten config, err := yaml.NewConfigWithFile("/home/cts/test/x.yml", ucfg.PathSep(".")) if err != nil { fmt.Println(err) os.Exit(1) } err = config.Unpack(&appConfig) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("counter:%d, age:%d\n", appConfig.Counter, appConfig.Person.Age) }
#x.yml
config.age: 18 counter: 8
或者
#x.yml
config: age: 18 counter: 9
运行结果:
cts@cts-pc:~/test$ ./test
counter:9, age:18

浙公网安备 33010602011771号