config

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package config provides typed configuration loading for Astra applications. It loads environment variables from .env files, YAML, and TOML and provides type-safe getters.

Package config provides environment variable loading and typed configuration access. Loads .env files on application startup, mirroring Astra's Env module.

Usage:

config.LoadEnv(".env")               // loads .env file into os environment
config.LoadEnv(".env.production")    // override with production settings

The .env file format supports:

  • KEY=value
  • KEY="quoted value"
  • KEY='single quoted value'
  • # comments
  • Empty lines
  • Variable expansion: KEY=${OTHER_KEY}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnvGet

func EnvGet(key string, defaultValue ...string) string

EnvGet returns an environment variable value or a default.

func EnvGetBool

func EnvGetBool(key string, defaultValue ...bool) bool

EnvGetBool returns an environment variable as a boolean.

func EnvGetDuration

func EnvGetDuration(key string, defaultValue ...time.Duration) time.Duration

EnvGetDuration returns an environment variable as a time.Duration. Accepts formats like "5s", "10m", "1h".

func EnvGetFloat

func EnvGetFloat(key string, defaultValue ...float64) float64

EnvGetFloat returns an environment variable as a float64.

func EnvGetInt

func EnvGetInt(key string, defaultValue ...int) int

EnvGetInt returns an environment variable as an integer.

func EnvGetOrFail

func EnvGetOrFail(key string) (string, error)

EnvGetOrFail returns an environment variable value or error if not set.

func Get

func Get[T any](c *Config, key string) T

Get retrieves a configuration value and casts it to T.

func LoadEnv

func LoadEnv(path string) error

LoadEnv loads a .env file and sets the values in the process environment. Existing environment variables are NOT overwritten (real env takes precedence).

func LoadEnvOverride

func LoadEnvOverride(path string) error

LoadEnvOverride loads a .env file, overwriting existing variables.

Types

type AppConfig

type AppConfig struct {
	Name            string        `env:"APP_NAME"`
	Environment     string        `env:"APP_ENV"`
	Host            string        `env:"HOST"`
	Port            int           `env:"PORT"`
	Debug           bool          `env:"APP_DEBUG"`
	Key             string        `env:"APP_KEY"`
	MaxBodySize     int64         `env:"APP_MAX_BODY_SIZE"`
	Version         string        `env:"APP_VERSION"`
	EncryptionKey   string        `env:"APP_ENCRYPTION_KEY"`
	AuditLogPath    string        `env:"AUDIT_LOG_PATH"`
	ShutdownTimeout time.Duration `env:"APP_SHUTDOWN_TIMEOUT"`
	TrustedProxies  []string      `env:"TRUSTED_PROXIES"`
}

AppConfig holds general application settings.

type AssetConfig

type AssetConfig struct {
	Entrypoints []string // e.g. ["resources/js/app.js", "resources/css/app.css"]
	OutputDir   string   // e.g. "public/build"
	PublicPath  string   // e.g. "/build/"
	Minify      bool
	Sourcemap   bool
	Manifest    string // e.g. "public/build/manifest.json"
}

AssetConfig holds asset pipeline configuration.

type AstraConfig

type AstraConfig struct {
	App       AppConfig
	Database  DatabaseConfig
	Redis     RedisConfig
	Auth      AuthConfig
	OAuth2    OAuth2Config
	Storage   StorageConfig
	Mail      MailConfig
	Queue     QueueConfig
	Telemetry TelemetryConfig
	Assets    AssetConfig
	WS        WSConfig
}

AstraConfig is the root configuration struct for all Astra services.

func LoadFromEnv

func LoadFromEnv(c *Config) *AstraConfig

LoadFromEnv creates an AstraConfig populated from environment variables.

func (*AstraConfig) Validate

func (c *AstraConfig) Validate() error

Validate checks that all required AstraConfig fields are set. Call this at application startup to fail fast on misconfiguration.

func (*AstraConfig) ValidateProduction

func (c *AstraConfig) ValidateProduction() error

ValidateProduction performs stricter validation for production environments.

func (*AstraConfig) ValidateRequired

func (c *AstraConfig) ValidateRequired(keys ...string) error

ValidateRequired returns an error if any of the named env vars are empty strings. Usage: cfg.ValidateRequired("STRIPE_KEY", "SENDGRID_KEY")

type AuthConfig

type AuthConfig struct {
	JWTSecret          string        `env:"JWT_SECRET"`
	JWTIssuer          string        `env:"JWT_ISSUER"`
	AccessTokenExpiry  time.Duration `env:"JWT_ACCESS_EXPIRY"`
	RefreshTokenExpiry time.Duration `env:"JWT_REFRESH_EXPIRY"`
}

AuthConfig holds authentication settings.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config holds loaded configuration and provides typed access.

func Load

func Load(paths ...string) (*Config, error)

Load creates a new Config by loading configuration from .env, YAML, and TOML files. Priority (highest wins): Env vars > .env > YAML > TOML.

func (*Config) Bool

func (c *Config) Bool(key string, def bool) bool

Bool returns the boolean value for the given key, or the default.

func (*Config) Duration

func (c *Config) Duration(key string, def time.Duration) time.Duration

Duration returns the time.Duration value for the given key, or the default.

func (*Config) Int

func (c *Config) Int(key string, def int) int

Int returns the integer value for the given key, or the default.

func (*Config) Int32

func (c *Config) Int32(key string, def int32) int32

Int32 returns the int32 value for the given key, or the default.

func (*Config) IsDev

func (c *Config) IsDev() bool

IsDev returns true if APP_ENV is "development" or "dev".

func (*Config) IsProd

func (c *Config) IsProd() bool

IsProd returns true if APP_ENV is "production" or "prod".

func (*Config) IsTest

func (c *Config) IsTest() bool

IsTest returns true if APP_ENV is "test" or "testing".

func (*Config) MaskSecrets

func (c *Config) MaskSecrets() map[string]any

MaskSecrets returns a copy of the config data with sensitive values masked.

func (*Config) Raw

func (c *Config) Raw() map[string]any

Raw returns the underlying config map.

func (*Config) String

func (c *Config) String(key string, def string) string

String returns the value for the given key, or the default if not set.

type DatabaseConfig

type DatabaseConfig struct {
	Connection      string        `env:"DB_CONNECTION"`
	URL             string        `env:"DATABASE_URL"`
	MaxConns        int32         `env:"DB_MAX_CONNS"`
	MinConns        int32         `env:"DB_MIN_CONNS"`
	MaxIdle         time.Duration `env:"DB_MAX_IDLE"`
	SSL             string        `env:"DB_SSL"`
	LogQueries      bool          `env:"DB_LOG_QUERIES"`
	SlowQueryThresh time.Duration `env:"DB_SLOW_QUERY_THRESH"`
	NeonAPIKey      string        `env:"NEON_API_KEY"`
	NeonProjectID   string        `env:"NEON_PROJECT_ID"`
}

DatabaseConfig holds connection settings, including Neon specific configuration.

type MailConfig

type MailConfig struct {
	Driver       string `env:"MAIL_DRIVER"`
	SMTPHost     string `env:"SMTP_HOST"`
	SMTPPort     int    `env:"SMTP_PORT"`
	SMTPUser     string `env:"SMTP_USER"`
	SMTPPassword string `env:"SMTP_PASSWORD"`
	SMTPFrom     string `env:"SMTP_FROM"`
	ResendAPIKey string `env:"RESEND_API_KEY"`
}

MailConfig holds mailer settings.

type OAuth2Config

OAuth2Config holds OAuth2 provider configurations.

type OAuth2ProviderEnvConfig

type OAuth2ProviderEnvConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string
}

OAuth2ProviderEnvConfig holds the env-loaded config for a single OAuth2 provider.

type QueueConfig

type QueueConfig struct {
	Driver      string   `env:"QUEUE_DRIVER"`
	Concurrency int      `env:"QUEUE_CONCURRENCY"`
	Prefix      string   `env:"QUEUE_PREFIX"`
	Queues      []string `env:"QUEUE_QUEUES"`
}

QueueConfig holds background queue settings.

type RedisConfig

type RedisConfig struct {
	URL            string   `env:"REDIS_URL"`
	Host           string   `env:"REDIS_HOST"`
	Port           int      `env:"REDIS_PORT"`
	Password       string   `env:"REDIS_PASSWORD"`
	DB             int      `env:"REDIS_DB"`
	MaxRetries     int      `env:"REDIS_MAX_RETRIES"`
	PoolSize       int      `env:"REDIS_POOL_SIZE"`
	UseSentinel    bool     `env:"REDIS_USE_SENTINEL"`
	SentinelMaster string   `env:"REDIS_SENTINEL_MASTER"`
	SentinelAddrs  []string `env:"REDIS_SENTINEL_ADDRS"`
	UseCluster     bool     `env:"REDIS_USE_CLUSTER"`
}

RedisConfig holds Redis connection settings.

type StorageConfig

type StorageConfig struct {
	Driver           string `env:"STORAGE_DRIVER"`
	LocalRoot        string `env:"STORAGE_LOCAL_ROOT"`
	S3Bucket         string `env:"S3_BUCKET"`
	S3Region         string `env:"S3_REGION"`
	S3Endpoint       string `env:"S3_ENDPOINT"`
	S3AccessKey      string `env:"S3_ACCESS_KEY"`
	S3SecretKey      string `env:"S3_SECRET_KEY"`
	S3ForcePathStyle bool   `env:"S3_FORCE_PATH_STYLE"`
}

StorageConfig holds file storage settings.

type TelemetryConfig

type TelemetryConfig struct {
	Endpoint    string `env:"OTEL_EXPORTER_OTLP_ENDPOINT"`
	ServiceName string `env:"OTEL_SERVICE_NAME"`
	MaxEntries  int    `env:"TELEMETRY_MAX_ENTRIES"`
}

TelemetryConfig holds OpenTelemetry and dev dashboard settings.

type WSConfig

type WSConfig struct {
	AllowedOrigins []string `env:"WS_ALLOWED_ORIGINS"`
}

WSConfig holds WebSocket settings.

Jump to

Keyboard shortcuts

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