Zero-effort, concise configuration management that avoids boilerplate and repetitive actions.
Zero-effort, concise configuration management that avoids boilerplate and repetitive actions.
I've always loved the elegance of Go's flag package - how clean and straightforward it is to define and use configuration options. While working on various Go projects, I found myself wanting that same simplicity but with support for YAML configs. I couldn't find anything that preserved this paradigm, so I built zerocfg.
flag packagego get -u github.com/chaindead/zerocfg….) are used as separators for hierarchical options._), and dash (-) styles.Example:
zfg.Str("groupOptions.thisOption", "", "camelCase usage")
zfg.Str("group_options.this_option", "", "underscore usage")
zfg.Str("group-options.this-option", "", "dash usage")Options are registered at import time. Dynamic (runtime) option registration is not supported
// internal/db/client.go
package db
import zfg "github.com/chaindead/zerocfg"
// good: options registered at import
var dbHost = zfg.Str("db.host", "localhost", "called on import")
// bad: dynamic registration
func AddOption() {
zfg.Str("db.dynamic", "", "not supported")
}No key duplication is allowed. Each option key must be unique to ensure a single source of truth and avoid boilerplate
Simultaneous use of keys and sub-keys (e.g., map and map.value) are not allowed
If zfg.Parse encounters an unknown value (e.g. variable not registered as an option), it returns an error.
This helps avoid boilerplate and ensures only declared options are used.
But you can ignore unknown values if desired.
err := zfg.Parse(
env.New(),
yaml.New(path),
)
if u, ok := zfg.IsUnknown(err); !ok {
panic(err)
} else {
// u is map to slice of unknown keys
fmt.Println(u)
}
envsource does not trigger unknown options to avoid false positives.
fmt.Sprint("%v")String() method, it is used for string conversion (e.g., time.Duration).For converting any value to string,
zfg.ToStringis used internally.
var (
_ = zfg.Dur("timeout", 5*time.Second, "duration via fmt.Stringer interface")
_ = zfg.Floats64("floats", nil, "list via json")
)
func main() {
_ = zfg.Parse()
fmt.Printf(zfg.Show())
// CMD: go run ./... --timeout 10s --floats '[1.1, 2.2, 3.3]'
// OUTPUT:
// floats = [1.1,2.2,3.3] (list via json)
// timeout = 10s (duration via fmt.Stringer interface)
}
The configuration system follows a strict priority hierarchy:
For example, if you initialize configuration like this:
zfg.Parse(
env.New(), // Second highest priority (after cli flags)
yaml.New(path), // Third highest priority
)The final value resolution order will be:
zfg.Parse in same order as it is passed.Important notes:
Parse() function= allowed)-) and double dash (--) prefixes are supported for flags and their aliasesExample:
path := zfg.Str("config.path", "", "path to yaml conf file", zfg.Alias("c"))You can run your application with:
go run ./... -c test.yaml
# or
go run ./... --config.path test.yamlIn both cases, the value test.yaml will be assigned to config.path.
Environment variables are automatically transformed from the configuration key format:
| Config Key | Environment Variable | Note |
|---|---|---|
| db.user | DB_USER | Basic transformation |
| app.api.key | APP_API_KEY | Multi-level path |
| camelCase.value | CAMELCASE_VALUE | CamelCase handling |
| api-key.secret | APIKEY_SECRET | Dashes removed |
| under_score.value | UNDERSCORE_VALUE | Underscores removed |
The transformation rules:
Example:
import (
"fmt"
zfg "github.com/chaindead/zerocfg"
"github.com/chaindead/zerocfg/env"
)
var dbUser = zfg.Str("db.user", "", "database's username")
func main() {
_ = zfg.Parse(
env.New(),
)
fmt.Printf("DB user: %s", *dbUser)
}When you run, dbUser will be set to admin.
DB_USER=admin go run main.go
# OUTPUT: DB user: adminExample YAML file:
group:
option: "foo"
numbers:
- 1
- 2
- 3
limits:
max: 10
min: 1Example Go config:
zfg.Str("group.option", "", "hierarchical usage")
zfg.Ints("numbers", nil, "slice of server configs")
zfg.Map("limits", nil, "map of limits")[!IMPORTANT] Read this section before implementing custom options or providers.
- All supported option values must have a string representation
- Conversion to string is performed using
zfg.ToString- Types must implement
Set(string); the string passed is produced byToStringand parsing must be compatible- Providers return
map[string]stringwhere values are produced by theconvfunction argument in the provider interface (internallyzfg.ToStringis used)
You can define your own option types by implementing the Value interface and registering them via Any function.
Methods Set and String should be compatible.
// Custom type
type MyType struct{ V string }
func newValue(val MyType, p *MyType) zfg.Value {
*p = val
return p
}
func (m *MyType) Set(s string) error { m.V = s; return nil }
func (m *MyType) Type() string { return "custom" }
func (m *MyType) String() string { return m.V }
func Custom(name string, defVal MyType, desc string, opts ...zfg.OptNode) *MyType {
return zfg.Any(name, defVal, desc, newValue, opts...)
}
// Register custom option
var myOpt = Custom("custom.opt", MyType{"default"}, "custom option")You can add your own configuration sources by implementing the Provider interface.
awaited[name] == true, the name is an optionawaited[name] == false, the name is an aliastype MyProvider struct{}
func (p *MyProvider) Type() string { return "my" }
func (p *MyProvider) Provide(awaited map[string]bool, conv func(any) string) (map[string]string, map[string]string, error) {
found := map[string]string{}
unknown := map[string]string{}
// ... fill found/unknown based on awaited ...
return found, unknown, nil
}
// Usage
zfg.Parse(&MyProvider{})For detailed documentation and advanced usage examples, visit our Godoc page.
This project is licensed under the MIT License - see the LICENSE file for details.
No open issues yet, or sync has not completed.