config

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 14 Imported by: 0

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:

  1. Base file: config.yaml (or config.env)
  2. Env file: config.<env>.yaml (e.g. config.dev.yaml)
  3. 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

View Source
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

func Load(dir, env string, out any) error

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

func LoadENV

func LoadENV(path string) error

LoadENV loads a single .env file into the process environment.

func LoadYAML

func LoadYAML(path string, out any) error

LoadYAML loads a single YAML file into out (no env layering).

func SetEnv

func SetEnv(key, value string) error

SetEnv sets a value in the process environment (os.Setenv). This is a convenience for making config values visible to libraries that read env vars directly.

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 Format

type Format int

Format is the configuration file format.

const (
	// FormatAuto auto-detects from file extension (.yaml/.yml → YAML, .env → ENV).
	FormatAuto Format = iota
	// FormatYAML forces YAML parsing.
	FormatYAML
	// FormatENV forces .env parsing.
	FormatENV
)

func (Format) String

func (f Format) String() string

String returns the format 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) BaseName

func (l *Loader) BaseName(name string) *Loader

BaseName sets the base filename without extension (default: "config").

func (*Loader) Dir

func (l *Loader) Dir(dir string) *Loader

Dir sets the config directory.

func (*Loader) Env

func (l *Loader) Env(env string) *Loader

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) Format

func (l *Loader) Format(f Format) *Loader

Format sets the file format (default: auto-detect).

func (*Loader) Load

func (l *Loader) Load(out any) error

Load loads configuration into the given struct pointer. It applies layers in order: base file → env-specific file → OS env vars.

func (*Loader) OverwriteEnvVars

func (l *Loader) OverwriteEnvVars(enabled bool) *Loader

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

func (l *Loader) WithEnvVars(enabled bool) *Loader

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:

  1. In-memory cache (TTL)
  2. Database configs table (if DB is configured)
  3. OS environment variable / .env file

func NewEnvOnlyStore

func NewEnvOnlyStore() (*Store, error)

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

func NewStoreWithDB(db *gorm.DB) (*Store, error)

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

func (s *Store) AutoMigrate() error

AutoMigrate creates the configs table if it doesn't exist and DB is set.

func (*Store) CheckValue

func (s *Store) CheckValue(key, defaultValue, format string, autoload, public bool) error

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) Close

func (s *Store) Close() error

Close releases cache resources.

func (*Store) DeleteValue

func (s *Store) DeleteValue(key string) error

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

func (s *Store) GetBoolValue(key string) bool

GetBoolValue returns the config value as bool. Returns false when unset/invalid.

func (*Store) GetBoolValueWithDefault

func (s *Store) GetBoolValueWithDefault(key string, defaultVal bool) bool

GetBoolValueWithDefault returns the config value as bool, or defaultVal when unset.

func (*Store) GetDurationValue

func (s *Store) GetDurationValue(key string, defaultVal time.Duration) time.Duration

GetDurationValue returns the config value as time.Duration (e.g. "30s", "5m").

func (*Store) GetFloatValue

func (s *Store) GetFloatValue(key string, defaultVal float64) float64

GetFloatValue returns the config value as float64, or defaultVal when unset/invalid.

func (*Store) GetInt64Value

func (s *Store) GetInt64Value(key string, defaultVal int64) int64

GetInt64Value returns the config value as int64, or defaultVal when unset/invalid.

func (*Store) GetIntValue

func (s *Store) GetIntValue(key string, defaultVal int) int

GetIntValue returns the config value as int, or defaultVal when unset/invalid.

func (*Store) GetStringWithDefault

func (s *Store) GetStringWithDefault(key, defaultVal string) string

GetStringWithDefault returns the config value, or defaultVal when unset.

func (*Store) GetValue

func (s *Store) GetValue(key string) string

GetValue returns the config value for key. Lookup order:

  1. In-memory cache (TTL)
  2. Database configs table (if DB is configured)
  3. OS environment variable / .env file

Returns "" when the key is not found in any source.

func (*Store) HasDB

func (s *Store) HasDB() bool

HasDB reports whether the store has a database backend.

func (*Store) LoadAutoloads

func (s *Store) LoadAutoloads() error

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

func (s *Store) LookupValue(key string) (string, bool)

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

func (s *Store) PurgeCache(key string)

PurgeCache evicts a single key from the in-memory cache.

func (*Store) SetValue

func (s *Store) SetValue(key, value, format string, autoload, public bool) error

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

func (s *Store) SetValueSimple(key, value string) error

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL