The config package provides a flexible configuration management system with support for multiple sources and formats.
- Multiple Configuration Sources
- Files (YAML, JSON, TOML)
- Environment Variables
- Command Line Flags
- Dynamic Configuration Updates
- Type-safe Access
- Default Values
- Configuration Validation
- Nested Configuration Support
import "github.com/ducconit/gocore/config"
// Create new configuration
cfg := config.New()
// Load from file
err := cfg.LoadFile("config.yaml")
if err != nil {
log.Fatal(err)
}
// Access values
port := cfg.GetInt("server.port")
host := cfg.GetString("server.host")
debug := cfg.GetBool("app.debug")
// Load from environment
cfg.LoadEnv()
// Access with fallback
dbHost := cfg.GetString("DB_HOST", "localhost")
cfg := config.New(
config.WithFile("config.yaml"),
config.WithEnv(),
config.WithFlags(),
)
// Basic getters
str := cfg.GetString("key")
num := cfg.GetInt("key")
float := cfg.GetFloat64("key")
bool := cfg.GetBool("key")
duration := cfg.GetDuration("key")
// With default values
str := cfg.GetString("key", "default")
num := cfg.GetInt("key", 8080)
// Typed getters
var serverConfig ServerConfig
cfg.Get("server", &serverConfig)
cfg.Set("key", "value")
cfg.SetDefault("server.port", 8080)
app:
name: MyApp
debug: true
server:
host: localhost
port: 8080
database:
host: localhost
port: 5432
name: mydb
user: user
password: password
APP_NAME=MyApp
SERVER_PORT=8080
DB_HOST=localhost
type DatabaseConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Name string `yaml:"name"`
User string `yaml:"user"`
Password string `yaml:"password"`
}
var dbConfig DatabaseConfig
cfg.Get("database", &dbConfig)
cfg.OnChange(func(e config.ChangeEvent) {
log.Printf("Config changed: %s = %v", e.Key, e.NewValue)
// Reload specific components
if e.Key == "database.host" {
reconnectDatabase()
}
})
type ServerConfig struct {
Host string `yaml:"host" validate:"required"`
Port int `yaml:"port" validate:"required,min=1024,max=65535"`
}
var serverConfig ServerConfig
if err := cfg.GetValidated("server", &serverConfig); err != nil {
log.Fatal(err)
}
- Use structured configuration
- Implement validation for critical values
- Provide sensible defaults
- Use environment variables for sensitive data
- Document configuration options
- Handle configuration errors gracefully
The package follows this configuration hierarchy (highest to lowest priority):
- Command Line Flags
- Environment Variables
- Configuration Files
- Default Values
- Never commit sensitive data in configuration files
- Use environment variables for secrets
- Implement proper access controls
- Validate configuration values
- Use secure storage for sensitive data