config

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 7 Imported by: 0

README

Type-Safe Config

Nimbus provides a type-safe configuration system that loads from .env.

Type-Safe Get

config.LoadAuto()  // loads .env and populates store

name := config.Get[string]("app.name")
port := config.Get[int]("server.port")
debug := config.Get[bool]("app.debug")

// With default
name := config.GetOrDefault[string]("app.name", "nimbus")

// Panic if missing
port := config.Must[int]("server.port")

Schema-Based (Struct)

type AppConfig struct {
    Port int    `config:"app.port" env:"PORT" default:"3333"`
    Env  string `config:"app.env" env:"APP_ENV" default:"development"`
    Name string `config:"app.name" env:"APP_NAME" default:"nimbus"`
}

config.LoadAuto()
var cfg AppConfig
config.LoadInto(&cfg)

Struct tags:

  • config:"key" — dot-notation key (e.g. app.name)
  • env:"VAR" — env var (e.g. APP_NAME)
  • default:"value" — fallback when missing

Load

config.LoadAuto()           // .env from current dir
config.LoadFromEnv(".env")  // explicit path

Custom Env Mapping

config.AddEnvMapping("CUSTOM_VAR", "custom.key")
config.LoadFromEnv()

Migrating Existing Apps

  1. Replace godotenv.Load() with nimbusconfig.LoadAuto() in your config.Load().
  2. Use cfg(key, fallback) or config.GetOrDefault[T](key, default) instead of env() for app/database keys.
  3. Add env mappings if needed: nimbusconfig.AddEnvMapping("VAR", "section.key") before LoadAuto().

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddEnvMapping

func AddEnvMapping(envKey, configKey string)

AddEnvMapping adds env var -> config key mapping (e.g. "CUSTOM_VAR" -> "custom.key").

func Get

func Get[T any](key string) (T, bool)

Get returns a config value by dot-notation key. Type-safe via generic. Returns zero value and false if key not found or conversion fails.

config.Get[string]("app.name")
config.Get[int]("server.port")
config.Get[bool]("app.debug")

func GetOrDefault

func GetOrDefault[T any](key string, defaultVal T) T

GetOrDefault returns the value or default if not found.

func LoadAuto

func LoadAuto() error

LoadAuto loads .env and populates the config store from environment variables.

func LoadFromEnv

func LoadFromEnv(paths ...string)

LoadFromEnv loads .env and merges into store. Call AddEnvMapping to customize.

func LoadInto

func LoadInto(dest any) error

LoadInto fills dest from the config store. Use struct tags:

config:"app.name"   - dot-notation key
env:"APP_NAME"      - env var (overrides config if set)
default:"value"     - fallback when missing

Example:

type AppConfig struct {
    Port int    `config:"server.port" env:"PORT" default:"3333"`
    Env  string `config:"app.env" env:"APP_ENV" default:"development"`
    Name string `config:"app.name" env:"APP_NAME" default:"nimbus"`
}
var cfg AppConfig
config.LoadInto(&cfg)

func Must

func Must[T any](key string) T

Must returns the value or panics if not found. Use when key is required.

func Require

func Require[T any](key string) (T, error)

Require returns the value or an error if not found/convertible. Prefer this in runtime request paths where panics are undesirable.

func Required

func Required(keys ...string) error

Required is a shorthand for validating that one or more env vars are set.

config.Required("APP_KEY", "DB_DSN")

func ValidateEnv

func ValidateEnv(rules ...EnvRule) error

ValidateEnv checks the environment against a set of rules. Returns an error listing all violations. If no violations exist, returns nil.

Usage:

err := config.ValidateEnv(
    config.EnvRule{Key: "APP_KEY", Required: true},
    config.EnvRule{Key: "APP_ENV", OneOf: []string{"development", "staging", "production"}, Default: "development"},
    config.EnvRule{Key: "DB_DRIVER", Required: true, OneOf: []string{"sqlite", "postgres", "mysql"}},
)
if err != nil {
    log.Fatal(err)
}

Types

type AppConfig

type AppConfig struct {
	Port string
	Env  string
	Name string
	Key  string // APP_KEY — secret backing session encryption and HMAC token signing

	// HTTP server timeouts. Zero disables a given timeout (stdlib default,
	// NOT recommended in production — a client can hold a connection open
	// indefinitely, enabling Slowloris-style resource exhaustion). Safe
	// defaults are applied by Load(); override via env.
	ReadTimeout       time.Duration // SERVER_READ_TIMEOUT
	ReadHeaderTimeout time.Duration // SERVER_READ_HEADER_TIMEOUT
	WriteTimeout      time.Duration // SERVER_WRITE_TIMEOUT
	IdleTimeout       time.Duration // SERVER_IDLE_TIMEOUT
	ShutdownTimeout   time.Duration // SERVER_SHUTDOWN_TIMEOUT
	MaxHeaderBytes    int           // SERVER_MAX_HEADER_BYTES
}

AppConfig is app-level config (port, env, app key).

type Config

type Config struct {
	App      AppConfig
	Database DatabaseConfig
}

Config holds application and provider configs (AdonisJS config/ style). It is intentionally small and focused; larger applications are encouraged to build their own typed config structs on top using LoadAuto / LoadInto.

func Current

func Current() *Config

Current returns the last Config loaded via Load, or nil if Load has not been called yet. This is primarily useful for tests and tooling that need to inspect the effective configuration without re-parsing the environment.

func Load

func Load() *Config

Load reads .env and builds Config (convention: config/*). For type-safe config, use Get[T], LoadInto, or LoadAuto.

func (*Config) IsProduction

func (c *Config) IsProduction() bool

IsProduction reports whether the app is running in a production environment.

func (*Config) Validate

func (c *Config) Validate() (warnings []string, err error)

Validate performs fail-closed runtime validation of the loaded config.

In production it returns an error when APP_KEY is missing or too short — booting with an empty/weak key would make session encryption and HMAC token signing predictable. Outside production a missing key is tolerated (dev convenience) and reported via the returned warnings slice instead.

Callers should treat a non-nil error as fatal (App.Boot does).

type DatabaseConfig

type DatabaseConfig struct {
	Driver string
	DSN    string
}

DatabaseConfig for database connection.

type EnvRule

type EnvRule struct {
	Key      string   // environment variable name
	Required bool     // must be set and non-empty
	OneOf    []string // if set, value must be one of these
	Default  string   // default value to set if missing (implies not required unless Required is true)
}

EnvRule describes a validation rule for an environment variable.

Jump to

Keyboard shortcuts

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