config

package
v0.1.36 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

config/appconfig.go

config/config.go

config/duration.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoadWithAppConfig added in v0.1.20

func LoadWithAppConfig(logger *zap.Logger, appEnvPrefix string, appKeys []AppKey) (*CoreConfig, AppConfigValues, error)

LoadWithAppConfig loads both WAFFLE core config and app-specific config. It merges defaults → config.* file(s) → env vars → explicit flags. Final precedence (highest wins): flags(explicit) > env > config > defaults.

The appEnvPrefix is used for BOTH core and app environment variables. This allows apps to have a unified prefix for all configuration. For example, if appEnvPrefix is "STRATA":

  • Core config: STRATA_HTTP_PORT, STRATA_LOG_LEVEL, etc.
  • App config: STRATA_MONGO_URI, STRATA_SESSION_NAME, etc.

If appEnvPrefix is empty, core config uses "WAFFLE" prefix for backward compatibility with existing deployments.

Config file keys and CLI flags use the key name directly (e.g., "session_name").

Example:

appKeys := []config.AppKey{
    {Name: "mongo_uri", Default: "mongodb://localhost:27017", Desc: "MongoDB connection URI"},
    {Name: "session_name", Default: "myapp-session", Desc: "Session cookie name"},
}
coreCfg, appCfg, err := config.LoadWithAppConfig(logger, "MYAPP", appKeys)
mongoURI := appCfg.String("mongo_uri")
// Environment variables: MYAPP_HTTP_PORT, MYAPP_MONGO_URI, etc.

Types

type AppConfigValues added in v0.1.20

type AppConfigValues map[string]any

AppConfigValues holds the loaded app configuration values. Keys are the AppKey.Name values, values are the loaded configuration.

func (AppConfigValues) Bool added in v0.1.20

func (a AppConfigValues) Bool(key string) bool

Bool returns a bool value or false if not found/wrong type.

func (AppConfigValues) Duration added in v0.1.26

func (a AppConfigValues) Duration(key string, def time.Duration) time.Duration

Duration parses a duration value from the config. Accepts:

  • Duration strings: "10m", "1h30m", "90s", "2h"
  • Numeric values: interpreted as seconds (e.g., 600 = 10 minutes)
  • Plain numeric strings: "600" = 600 seconds

Returns the default value if the key is not found, empty, or invalid. Use this for timeout, expiry, and interval configurations.

func (AppConfigValues) Int added in v0.1.20

func (a AppConfigValues) Int(key string) int

Int returns an int value or 0 if not found/wrong type. Handles both int and int64 (TOML/Viper returns int64 for integers).

func (AppConfigValues) Int64 added in v0.1.20

func (a AppConfigValues) Int64(key string) int64

Int64 returns an int64 value or 0 if not found/wrong type. Handles both int64 and int for flexibility.

func (AppConfigValues) String added in v0.1.20

func (a AppConfigValues) String(key string) string

String returns a string value or empty string if not found/wrong type.

func (AppConfigValues) StringSlice added in v0.1.20

func (a AppConfigValues) StringSlice(key string) []string

StringSlice returns a []string value or nil if not found/wrong type.

type AppKey added in v0.1.20

type AppKey struct {
	// Name is the key name (e.g., "session_name", "mongo_uri").
	// This is used as-is for config files and CLI flags.
	// For env vars, it's uppercased and prefixed (e.g., STRATAHUB_SESSION_NAME).
	Name string

	// Default is the default value if not set elsewhere.
	// Supported types: string, int, int64, bool, []string.
	Default any

	// Desc is a short description for --help output.
	Desc string
}

AppKey defines a configuration key for an application. Apps register their config keys using this type, and WAFFLE handles loading from config files, environment variables, and command-line flags.

type CORSConfig

type CORSConfig struct {
	EnableCORS           bool     `mapstructure:"enable_cors"`
	CORSAllowedOrigins   []string `mapstructure:"cors_allowed_origins"`
	CORSAllowedMethods   []string `mapstructure:"cors_allowed_methods"`
	CORSAllowedHeaders   []string `mapstructure:"cors_allowed_headers"`
	CORSExposedHeaders   []string `mapstructure:"cors_exposed_headers"`
	CORSAllowCredentials bool     `mapstructure:"cors_allow_credentials"`
	CORSMaxAge           int      `mapstructure:"cors_max_age"`
}

CORSConfig groups all CORS behavior and lists.

type CoreConfig

type CoreConfig struct {
	// runtime
	Env      string `mapstructure:"env"`       // "dev" | "prod"
	LogLevel string `mapstructure:"log_level"` // debug, info, warn, error …

	// grouped config
	HTTP     HTTPConfig     `mapstructure:",squash"`
	TLS      TLSConfig      `mapstructure:",squash"`
	CORS     CORSConfig     `mapstructure:",squash"`
	Security SecurityConfig `mapstructure:",squash"`

	// DB-related timeouts (no URIs/DB names here)
	DBConnectTimeout time.Duration `mapstructure:"db_connect_timeout"`
	IndexBootTimeout time.Duration `mapstructure:"index_boot_timeout"`

	// HTTP behavior
	MaxRequestBodyBytes int64 `mapstructure:"max_request_body_bytes"`

	// misc
	EnableCompression bool `mapstructure:"enable_compression"`
	CompressionLevel  int  `mapstructure:"compression_level"` // 1-9, default 5
}

CoreConfig holds the core configuration shared by all WAFFLE-based services.

func Load

func Load(logger *zap.Logger) (*CoreConfig, error)

Load merges defaults → config.* file(s) → env vars → explicit flags into one CoreConfig. Final precedence (highest wins): flags(explicit) > env > config > defaults.

For apps that need their own config keys, use LoadWithAppConfig instead.

func (CoreConfig) Dump

func (c CoreConfig) Dump() string

Dump returns a pretty, redacted JSON string of the config for debugging. Never logs secrets; use at debug level only.

type HTTPConfig

type HTTPConfig struct {
	HTTPPort  int  `mapstructure:"http_port"`
	HTTPSPort int  `mapstructure:"https_port"`
	UseHTTPS  bool `mapstructure:"use_https"`

	// Server timeouts
	ReadTimeout       time.Duration `mapstructure:"read_timeout"`
	ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"`
	WriteTimeout      time.Duration `mapstructure:"write_timeout"`
	IdleTimeout       time.Duration `mapstructure:"idle_timeout"`
	ShutdownTimeout   time.Duration `mapstructure:"shutdown_timeout"`
}

HTTPConfig groups HTTP/HTTPS port and protocol settings.

type SecurityConfig added in v0.1.34

type SecurityConfig struct {
	// EnableSecurityHeaders enables the security headers middleware.
	// Default: true (security headers are enabled by default)
	EnableSecurityHeaders bool `mapstructure:"enable_security_headers"`

	// XFrameOptions controls iframe embedding. Values: "DENY", "SAMEORIGIN"
	// Default: "SAMEORIGIN"
	XFrameOptions string `mapstructure:"x_frame_options"`

	// XContentTypeOptions prevents MIME sniffing. Should be "nosniff".
	// Default: "nosniff"
	XContentTypeOptions string `mapstructure:"x_content_type_options"`

	// ReferrerPolicy controls referrer information sent with requests.
	// Default: "strict-origin-when-cross-origin"
	ReferrerPolicy string `mapstructure:"referrer_policy"`

	// XSSProtection enables browser XSS filter. Values: "0", "1", "1; mode=block"
	// Default: "1; mode=block"
	XSSProtection string `mapstructure:"x_xss_protection"`

	// HSTSMaxAge sets Strict-Transport-Security max-age in seconds.
	// Only sent for HTTPS requests. Set to 0 to disable.
	// Default: 31536000 (1 year)
	HSTSMaxAge int `mapstructure:"hsts_max_age"`

	// HSTSIncludeSubDomains adds includeSubDomains to HSTS header.
	// Default: true
	HSTSIncludeSubDomains bool `mapstructure:"hsts_include_subdomains"`

	// HSTSPreload adds preload directive. Only enable if submitted to preload list.
	// Default: false
	HSTSPreload bool `mapstructure:"hsts_preload"`

	// ContentSecurityPolicy sets the CSP header. Leave empty to not set.
	// Example: "default-src 'self'; script-src 'self' 'unsafe-inline'"
	// Default: "" (not set - requires application-specific configuration)
	ContentSecurityPolicy string `mapstructure:"content_security_policy"`

	// PermissionsPolicy controls browser feature access. Leave empty to not set.
	// Example: "geolocation=(), microphone=(), camera=()"
	// Default: "" (not set)
	PermissionsPolicy string `mapstructure:"permissions_policy"`
}

SecurityConfig groups security header settings.

These headers provide defense-in-depth against common web attacks:

  • X-Frame-Options: Prevents clickjacking by controlling iframe embedding
  • X-Content-Type-Options: Prevents MIME type sniffing attacks
  • Referrer-Policy: Controls referrer information leakage
  • X-XSS-Protection: Legacy XSS filter for older browsers
  • Strict-Transport-Security: Forces HTTPS connections
  • Content-Security-Policy: Powerful XSS and injection prevention
  • Permissions-Policy: Controls access to browser features

type TLSConfig

type TLSConfig struct {
	CertFile            string `mapstructure:"cert_file"`
	KeyFile             string `mapstructure:"key_file"`
	UseLetsEncrypt      bool   `mapstructure:"use_lets_encrypt"`
	LetsEncryptEmail    string `mapstructure:"lets_encrypt_email"`
	LetsEncryptCacheDir string `mapstructure:"lets_encrypt_cache_dir"`

	// Domain is the single domain for TLS/ACME (backward compatible).
	// Use Domains for multiple domains on a single certificate.
	// Cannot specify both Domain and Domains.
	Domain string `mapstructure:"domain"`

	// Domains is a list of domains for a single certificate (e.g., ["example.com", "*.example.com"]).
	// Use this for wildcard + apex domain certificates.
	// Cannot specify both Domain and Domains.
	Domains []string `mapstructure:"domains"`

	// LetsEncryptChallenge selects which ACME challenge type to use when
	// UseLetsEncrypt is true. Supported values:
	//   - "http-01" (default; uses an HTTP challenge endpoint)
	//   - "dns-01"  (for use with Route 53 DNS TXT records; required for wildcards)
	LetsEncryptChallenge string `mapstructure:"lets_encrypt_challenge"`

	// Route53HostedZoneID is required when using DNS-01 with Route 53 so the
	// ACME client knows which hosted zone to update.
	Route53HostedZoneID string `mapstructure:"route53_hosted_zone_id"`

	// ACMEDirectoryURL is the ACME directory URL to use. Defaults to Let's Encrypt
	// production for prod env, staging for other environments. Common values:
	//   - Production: https://acme-v02.api.letsencrypt.org/directory
	//   - Staging:    https://acme-staging-v02.api.letsencrypt.org/directory
	ACMEDirectoryURL string `mapstructure:"acme_directory_url"`
}

TLSConfig groups all TLS / ACME-related settings.

func (TLSConfig) EffectiveDomains added in v0.1.27

func (t TLSConfig) EffectiveDomains() []string

EffectiveDomains returns the list of domains for certificate generation. It returns Domains if set, otherwise a single-element slice containing Domain. Returns nil if neither is configured.

Jump to

Keyboard shortcuts

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