https://github.com/peak/go-config
Load config files and watch for changes
https://github.com/peak/go-config
Last synced: about 1 year ago
JSON representation
Load config files and watch for changes
- Host: GitHub
- URL: https://github.com/peak/go-config
- Owner: peak
- License: mit
- Created: 2019-04-30T13:26:47.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2021-09-21T08:14:42.000Z (over 4 years ago)
- Last Synced: 2025-04-13T20:15:12.154Z (about 1 year ago)
- Language: Go
- Size: 33.2 KB
- Stars: 11
- Watchers: 8
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
- Codeowners: .github/CODEOWNERS
Awesome Lists containing this project
README
[](https://travis-ci.org/peak/go-config)
[](https://goreportcard.com/report/github.com/peak/go-config)
# go-config
Offers a rich configuration file handler.
- Read configuration files with ease
- Bind CLI flags
- Bind environment variables
- Watch file (or files) and get notified if they change
---
Uses the following precedence order:
* `flag`
* `env`
* `toml`
| flag | env | toml | result |
|:----:|:-----:|:-------------:|:---:|
| ☑ | ☑ | ☑ | **flag** |
| ☑ | ☑ | ☐ | **flag** |
| ☑ | ☐ | ☑ | **flag** |
| ☐ | ☑ | ☑ | **env** |
| ☑ | ☐ | ☐ | **flag** |
| ☐ | ☑ | ☐ | **env** |
| ☐ | ☐ | ☑ | **toml** |
If `flag` is set and not given, it will parse `env` or `toml` according to their precedence order (otherwise flag default).
## Basic Example
Call the `Load()` method to load a config.
```go
type MyConfig struct {
Key1 string `toml:"key1"`
Key2 string `toml:"key2"`
Port int `toml:"-" flag:"port"`
Secret string `toml:"-" flag:"-" env:"secret"`
}
_ = flag.Int("port", 8080, "Port to listen on") // <- notice no variable
flag.Parse()
var cfg MyConfig
err := config.Load("./config.toml", &cfg)
fmt.Printf("Loaded config: %#v\n", cfg)
// Port info is in cfg.Port, parsed from `-port` param
// Secret info is in cfg.Secret, parsed from `secret` environment variable
```
## File Watching
Call `Watch()` method, get a notification channel and listen...
```go
ch, err := config.Watch(context.Background(), "config.toml")
for {
select {
case e := <-ch:
if e != nil {
fmt.Printf("Error occured watching file: %v", e)
continue
}
fmt.Println("Changed, reloading...")
var cfg MyConfig
err := config.Load("config.toml", &cfg)
fmt.Printf("Loaded: %v %#v\n", err, cfg)
// Handle cfg...
}
}
```