A Go library for loading application configuration from multiple sources — YAML files, JSON files, and environment variables — with defined precedence rules and hot-reload support.
Built as a learning project to understand reflection, struct tags, and environment handling in Go.
- Load config from YAML and JSON files
- Override any value via environment variables
- Precedence: env vars > JSON > YAML > defaults
- Hot-reload: automatically detects file changes and reloads config
- Struct tags for mapping and default values
- Type coercion from string env vars to int, bool, duration, etc.
- Validation for required fields and value ranges
go get github.com/amit/config-loaderpackage main
import (
"fmt"
"log"
"time"
config "github.com/amit/config-loader"
)
type AppConfig struct {
Port int `yaml:"port" env:"APP_PORT" default:"8080"`
Debug bool `yaml:"debug" env:"APP_DEBUG" default:"false"`
Timeout time.Duration `yaml:"timeout" env:"APP_TIMEOUT" default:"30s"`
Database struct {
Host string `yaml:"host" env:"DB_HOST" required:"true"`
Port int `yaml:"port" env:"DB_PORT" default:"5432"`
Password string `yaml:"password" env:"DB_PASSWORD" required:"true"`
} `yaml:"database"`
}
func main() {
var cfg AppConfig
loader := config.New().
WithYAML("config.yaml").
WithJSON("config.json").
WithEnv().
WithHotReload()
if err := loader.Load(&cfg); err != nil {
log.Fatal(err)
}
fmt.Println("Server running on port:", cfg.Port)
}yaml:"key"- YAML key nameenv:"ENV_VAR"- Environment variable namedefault:"value"- Default value if not setrequired:"true"- Field must be set
Configuration sources are merged in this order (highest to lowest priority):
| Source | Priority |
|---|---|
| Environment Variables | Highest |
| JSON file | Medium |
| YAML file | Low |
| Struct tag defaults | Lowest |
Enable hot-reload to automatically reload configuration when files change:
loader := config.New().
WithYAML("config.yaml").
WithHotReload().
OnReload(func(cfg interface{}) {
fmt.Println("Config reloaded!")
})Changes are debounced (300ms) and reloading is goroutine-safe. If the new config is invalid, the old config is kept.
The library validates:
- Required fields are set
- Port numbers are between 1-65535
- Duration values are non-negative
Environment variables (strings) are automatically converted to:
int,int64float64bool(accepts "true", "false", "1", "0")time.Duration(e.g., "30s", "5m", "1h")
See examples/basic/ for a complete working example.
cd examples/basic
go run main.gogo test ./...gopkg.in/yaml.v3— YAML parsinggithub.com/fsnotify/fsnotify— File watching
MIT