DefaultConfig is a library for loading YAML configuration files and mapping data into a struct in Golang, using Viper. It supports environment variables and default values.
Add the library to your project:
go get -u github.com/anhnmt/go-defaultconfigtype Config struct {
Name string `mapstructure:"name" default:"default_name"`
Debug bool `mapstructure:"debug" default:"false"`
}name: "my_app"
debug: truepackage main
import (
"fmt"
"log"
)
func main() {
var cfg Config
err := defaultconfig.Load("./config", "dev", &cfg)
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
fmt.Printf("Loaded config: %+v\n", cfg)
}func Load(dir, env string, cfg any) errordir: Path to the directory containing the configuration files.env: Environment name (corresponding toconfig/{env}.yml).cfg: Pointer to the struct that receives the configuration data.
- Determines the configuration file path (
config/{env}.yml). - Reads the YAML file and maps it into
cfg. - Supports environment variables (converts
.to_). - Supports default values from the struct tag
default.
If environment variables are set:
export NAME="env_name"
export DEBUG=trueThe program will use these values instead of those in the YAML file.
# Run all tests
go test -v ./...MIT License