Documentation
¶
Overview ¶
Package config provides a multi-format, multi-environment configuration loader. It supports YAML and .env files with environment-specific overrides (e.g. config.yaml + config.dev.yaml).
Design ¶
Configurations are loaded in layers, each layer overriding the previous:
- Base file: config.yaml (or config.env)
- Env file: config.<env>.yaml (e.g. config.dev.yaml)
- OS env vars: override individual keys via struct tags
File layout ¶
config/ ├── config.yaml # base config (all environments) ├── config.dev.yaml # dev overrides ├── config.prod.yaml # prod overrides └── config.test.yaml # test overrides
Or using .env format:
config/ ├── config.env # base ├── config.dev.env # dev overrides
Quick start ¶
type AppCfg struct {
Server struct {
Port int `yaml:"port" env:"SERVER_PORT"`
} `yaml:"server"`
DB struct {
DSN string `yaml:"dsn" env:"DSN"`
} `yaml:"db"`
}
// Load from ./config/config.yaml + config.dev.yaml + OS env
var cfg AppCfg
err := config.Load("config/", "dev", &cfg)
if err != nil { log.Fatal(err) }
// Or use the Builder API for fine-grained control
cfg, err := config.New().
Dir("config/").
Env("dev").
LoadInto(&AppCfg{})
Index ¶
- Constants
- func Load(dir, env string, out any) error
- func LoadENV(path string) error
- func LoadYAML(path string, out any) error
- func SetEnv(key, value string) error
- type ConfigItem
- type Format
- type Loader
- func (l *Loader) BaseName(name string) *Loader
- func (l *Loader) Dir(dir string) *Loader
- func (l *Loader) Env(env string) *Loader
- func (l *Loader) Format(f Format) *Loader
- func (l *Loader) Load(out any) error
- func (l *Loader) OverwriteEnvVars(enabled bool) *Loader
- func (l *Loader) WithEnvVars(enabled bool) *Loader
- type Store
- func (s *Store) AllConfigs() ([]ConfigItem, error)
- func (s *Store) AutoMigrate() error
- func (s *Store) CheckValue(key, defaultValue, format string, autoload, public bool) error
- func (s *Store) Close() error
- func (s *Store) DeleteValue(key string) error
- func (s *Store) GetBoolValue(key string) bool
- func (s *Store) GetBoolValueWithDefault(key string, defaultVal bool) bool
- func (s *Store) GetDurationValue(key string, defaultVal time.Duration) time.Duration
- func (s *Store) GetFloatValue(key string, defaultVal float64) float64
- func (s *Store) GetInt64Value(key string, defaultVal int64) int64
- func (s *Store) GetIntValue(key string, defaultVal int) int
- func (s *Store) GetStringWithDefault(key, defaultVal string) string
- func (s *Store) GetValue(key string) string
- func (s *Store) HasDB() bool
- func (s *Store) LoadAutoloads() error
- func (s *Store) LoadPublicConfigs() ([]ConfigItem, error)
- func (s *Store) LookupValue(key string) (string, bool)
- func (s *Store) PurgeAllCache()
- func (s *Store) PurgeCache(key string)
- func (s *Store) SetValue(key, value, format string, autoload, public bool) error
- func (s *Store) SetValueSimple(key, value string) error
- type StoreOptions
Constants ¶
const ( ConfigFormatText = "text" ConfigFormatJSON = "json" ConfigFormatYAML = "yaml" ConfigFormatInt = "int" ConfigFormatFloat = "float" ConfigFormatBool = "bool" )
Supported format constants for ConfigItem.Format.
Variables ¶
This section is empty.
Functions ¶
func Load ¶
Load is a convenience function that creates a Loader and loads config.
- dir: config directory (e.g. "config/")
- env: environment name (e.g. "dev", "prod", "" for no env-specific file)
- out: pointer to the config struct
Types ¶
type ConfigItem ¶
type ConfigItem struct {
ID uint `json:"id" gorm:"primaryKey"`
Key string `json:"key" gorm:"size:128;uniqueIndex"`
Desc string `json:"desc" gorm:"size:200"`
Autoload bool `json:"autoload" gorm:"index"`
Public bool `json:"public" gorm:"index;default:false"`
Format string `json:"format" gorm:"size:20;default:text" comment:"json,yaml,int,float,bool,text"`
Value string `json:"value"`
CreatedAt time.Time `json:"-" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"-" gorm:"autoUpdateTime"`
}
ConfigItem represents a row in the configs table. It is used by Store to persist key/value configuration entries in a database. When no DB is configured, Store falls back to environment variables.
func (ConfigItem) TableName ¶
func (ConfigItem) TableName() string
TableName overrides the default table name.
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
Loader is the main configuration loader. Use New() to create one.
func New ¶
func New() *Loader
New creates a new Loader with sensible defaults:
- dir: "config/"
- baseName: "config"
- format: auto-detect
- envVars: true (OS env overrides take precedence)
func (*Loader) Env ¶
Env sets the environment name (e.g. "dev", "prod", "test"). When set, the loader looks for config.<env>.yaml as an override layer.
func (*Loader) Load ¶
Load loads configuration into the given struct pointer. It applies layers in order: base file → env-specific file → OS env vars.
func (*Loader) OverwriteEnvVars ¶
OverwriteEnvVars controls whether .env file values are written to os.Environ via os.Setenv (default: false). Useful for making values visible to libraries that read env vars directly.
func (*Loader) WithEnvVars ¶
WithEnvVars enables/disables OS env var overrides (default: enabled).
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a system configuration store. It can optionally persist configs to a database table and always falls back to environment variables when no DB is configured or a key is not found in the DB.
Lookup order for GetValue:
- In-memory cache (TTL)
- Database configs table (if DB is configured)
- OS environment variable / .env file
func NewEnvOnlyStore ¶
NewEnvOnlyStore creates a Store that reads only from env vars / .env files.
func NewStore ¶
func NewStore(opts StoreOptions) (*Store, error)
NewStore creates a new Store. db may be nil for env-only mode.
func NewStoreWithDB ¶
NewStoreWithDB is a convenience wrapper for NewStore with a DB and defaults.
func (*Store) AllConfigs ¶
func (s *Store) AllConfigs() ([]ConfigItem, error)
AllConfigs returns all config entries from the database. In env-only mode it returns nil.
func (*Store) AutoMigrate ¶
AutoMigrate creates the configs table if it doesn't exist and DB is set.
func (*Store) CheckValue ¶
CheckValue inserts a default config entry if the key does not exist. This is useful for seeding default values on first run. In env-only mode it sets the value in the in-process envStore.
func (*Store) DeleteValue ¶
DeleteValue removes a config entry from the database and cache. In env-only mode it only removes from the in-process envStore.
func (*Store) GetBoolValue ¶
GetBoolValue returns the config value as bool. Returns false when unset/invalid.
func (*Store) GetBoolValueWithDefault ¶
GetBoolValueWithDefault returns the config value as bool, or defaultVal when unset.
func (*Store) GetDurationValue ¶
GetDurationValue returns the config value as time.Duration (e.g. "30s", "5m").
func (*Store) GetFloatValue ¶
GetFloatValue returns the config value as float64, or defaultVal when unset/invalid.
func (*Store) GetInt64Value ¶
GetInt64Value returns the config value as int64, or defaultVal when unset/invalid.
func (*Store) GetIntValue ¶
GetIntValue returns the config value as int, or defaultVal when unset/invalid.
func (*Store) GetStringWithDefault ¶
GetStringWithDefault returns the config value, or defaultVal when unset.
func (*Store) GetValue ¶
GetValue returns the config value for key. Lookup order:
- In-memory cache (TTL)
- Database configs table (if DB is configured)
- OS environment variable / .env file
Returns "" when the key is not found in any source.
func (*Store) LoadAutoloads ¶
LoadAutoloads loads all configs with autoload=true into the cache. In env-only mode this is a no-op.
func (*Store) LoadPublicConfigs ¶
func (s *Store) LoadPublicConfigs() ([]ConfigItem, error)
LoadPublicConfigs loads all public configs into the cache and returns them. In env-only mode it returns nil.
func (*Store) LookupValue ¶
LookupValue returns the value and a found flag, similar to os.LookupEnv.
func (*Store) PurgeAllCache ¶
func (s *Store) PurgeAllCache()
PurgeAllCache evicts all entries from the in-memory cache.
func (*Store) PurgeCache ¶
PurgeCache evicts a single key from the in-memory cache.
func (*Store) SetValue ¶
SetValue upserts a config entry in the database and updates the cache. In env-only mode (no DB), it only updates the in-process envStore so that subsequent GetValue calls see the new value.
func (*Store) SetValueSimple ¶
SetValueSimple upserts a text-format, non-public, non-autoload config.
type StoreOptions ¶
type StoreOptions struct {
// DB is the GORM database handle. When nil, the store operates in
// env-only mode: GetValue reads from OS env vars and .env files,
// SetValue/CheckValue are no-ops on the DB, LoadAutoloads returns nothing.
DB *gorm.DB
// Cache is an optional cache.Cache[string, []byte] implementation for config values.
// When nil, an LRU cache with TTL is created automatically.
Cache cache.Cache[string, []byte]
// CacheSize is the max number of cached config entries (default 1024).
// Only used when Cache is nil.
CacheSize int
// CacheTTL is how long a cached entry is valid (default 10s).
// Only used when Cache is nil.
CacheTTL time.Duration
}
StoreOptions configures a Store.