It lets you define a set of default parameters, and extend them for different deployment environments (development, qa, staging, production, etc.).
$ mkdir config
$ vi config/default.json
{
"name": "app-name",
"dbConfig": {
"host": "localhost",
"port": 1
}
}
$ vi config/production.json
{
"dbConfig": {
"host": "prod-db-server"
}
}
$ vi config/local-production.json
{
"dbConfig": {
"port": 8000
}
}
Use configs in your code:
import (
gonfig "github.com/eduardbcom/gonfig"
)
type Config struct {
DbConfig struct {
Host string `json:"host"`
Port int `json:"port"`
} `json:"dbConfig"`
Name string `json:"name"`
}
appConfig := &Config{}
if rawData, err := gonfig.Read(); err != nil {
panic(err)
} else {
if err := json.Unmarshal(rawData, appConfig); err != nil {
panic(err)
} else {
fmt.Printf(
"{\"name\": \"%s\", \"dbConfig\": {\"host\": \"%s\", port: \"%d\"}}\n",
appConfig.Name,
appConfig.DbConfig.Host,
appConfig.DbConfig.Port
) // {"name": "new-awesome-name", "dbConfig": {"host": "prod-db-server", port: "1"}}
}
}
$ export APP_ENV=production
$ go run app.go --config='{"name": "new-app-name"}'
Only json
file format is supported.
In order to validate configuration using json schema
format you need to create schema
folder and pass it via --schema_dir
param. By default library searches schema
folder near the application executable file and silently skips schema verification in case folder does not exist.
schema/index.json
is the entry point of schema.
Only draft-04
is supported. Under the hood validate-json is used for schema validation.
See the example folder.