config

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Redact

func Redact(cfg any) any

Redact returns a shallow copy of the config struct with all fields tagged sensitive:"true" replaced by "***". Works on any struct (including nested ones). The original struct is never modified.

Use this before logging or serializing config to prevent credential leaks:

logger.Info("config loaded", "config", config.Redact(&cfg))

Types

type AccountOptions

type AccountOptions struct {
	Enabled         bool          `mapstructure:"enabled"          default:"false"`
	SigningKey      string        `mapstructure:"signing_key"       sensitive:"true"`
	Expiration      time.Duration `mapstructure:"expiration"       default:"2h"`
	ResetExpiration time.Duration `mapstructure:"reset_expiration" default:"15m"`
	// LoginRateWindow + LoginRateLimit configure per-email login attempt
	// throttling on /login. When both are positive the account module
	// installs a sliding-window limiter; on threshold exceedance the
	// endpoint returns 429 Too Many Requests. Both zero (the default)
	// disables the limiter entirely. Recommended production values:
	// window=15m, limit=10.
	LoginRateWindow time.Duration `mapstructure:"login_rate_window"`
	LoginRateLimit  int           `mapstructure:"login_rate_limit"`
}

func (AccountOptions) GoString

func (o AccountOptions) GoString() string

GoString implements fmt.GoStringer for AccountOptions.

func (AccountOptions) String

func (o AccountOptions) String() string

String implements fmt.Stringer for AccountOptions.

func (*AccountOptions) Validate

func (o *AccountOptions) Validate() error

type CacheFileOptions

type CacheFileOptions struct {
	Enabled bool          `mapstructure:"enabled" default:"false"`
	Path    string        `mapstructure:"path"    default:".cache"`
	TTL     time.Duration `mapstructure:"ttl"     default:"1h"`
}

func (*CacheFileOptions) Validate

func (o *CacheFileOptions) Validate() error

type CacheMemoryOptions

type CacheMemoryOptions struct {
	Enabled  bool          `mapstructure:"enabled"  default:"false"`
	Capacity int           `mapstructure:"capacity" default:"10000"`
	TTL      time.Duration `mapstructure:"ttl"      default:"5m"`
}

func (*CacheMemoryOptions) Validate

func (o *CacheMemoryOptions) Validate() error

type DatabaseOptions

type DatabaseOptions struct {
	Driver string        `mapstructure:"driver"` // "sqlite" or "mysql"; empty = disabled
	SQLite SQLiteOptions `mapstructure:"sqlite"`
	MySQL  MySQLOptions  `mapstructure:"mysql"`
}

DatabaseOptions provides a discriminator-based database configuration. Instead of having separate MySQLOptions.Enabled and SQLiteOptions.Enabled fields (which can conflict), users set a single Driver field:

database:
  driver: sqlite
  sqlite:
    path: "app.db"
  mysql:
    host: "127.0.0.1"

When Driver is empty, the component is disabled. The Driver field selects which nested config block is used; the other is ignored.

func (*DatabaseOptions) Validate

func (o *DatabaseOptions) Validate() error

type DebugOptions

type DebugOptions struct {
	Enabled bool `mapstructure:"enabled" default:"false"`
}

DebugOptions configures the /componentz debug endpoint. Disabled by default — enable for development or staging environments to expose component topology and init timing via HTTP.

type HTTPOptions

type HTTPOptions struct {
	Enabled           bool          `mapstructure:"enabled"            default:"true"`
	Addr              string        `mapstructure:"addr"               default:":8080"`
	ReadTimeout       time.Duration `mapstructure:"read_timeout"       default:"30s"`
	WriteTimeout      time.Duration `mapstructure:"write_timeout"      default:"30s"`
	ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" default:"10s"`
	IdleTimeout       time.Duration `mapstructure:"idle_timeout"       default:"120s"`
	// RequestTimeout is the maximum duration for processing a single HTTP
	// request. When non-zero, a Timeout middleware is automatically added
	// to the middleware stack, cancelling the request context and returning
	// 504 if the handler does not complete in time. Zero disables the
	// middleware (the default).
	RequestTimeout time.Duration `mapstructure:"request_timeout"`
	// DrainDelay is the pause between marking /readyz as 503 and actually
	// stopping the HTTP server. In Kubernetes deployments this gives the
	// load balancer time to deregister the pod before in-flight requests
	// are drained. Default 5s; zero disables the delay.
	DrainDelay time.Duration `mapstructure:"drain_delay" default:"5s"`

	// TrustedProxies is the list of CIDRs / IPs whose X-Forwarded-For and
	// X-Real-IP headers gin may honour when computing c.ClientIP(). Empty
	// slice (the default) trusts NO proxy — c.ClientIP() returns the
	// direct socket peer. Set to ["127.0.0.1"] when fronted by a local
	// reverse proxy, ["10.0.0.0/8"] behind an in-cluster LB, etc.
	//
	// Not setting this means loginLimiter's IP-keyed bucket is bypassable
	// by any client spoofing X-Forwarded-For; the fail-closed default
	// avoids that trap.
	TrustedProxies []string `mapstructure:"trusted_proxies"`
}

func (*HTTPOptions) Validate

func (o *HTTPOptions) Validate() error

type HealthOptions

type HealthOptions struct {
	Enabled bool   `mapstructure:"enabled" default:"true"`
	Path    string `mapstructure:"path"    default:"/healthz"`
}

HealthOptions configures the /healthz endpoint. When Enabled is true and an HTTP server exists, the HealthComponent is auto-registered. Enabled defaults to true so health is available out of the box; set false to disable.

func (*HealthOptions) Validate

func (o *HealthOptions) Validate() error

type LogFileOptions

type LogFileOptions struct {
	Path       string `mapstructure:"path"`
	MaxSizeMB  int    `mapstructure:"max_size_mb"  default:"100"`
	MaxBackups int    `mapstructure:"max_backups"  default:"7"`
	MaxAgeDays int    `mapstructure:"max_age_days" default:"30"`
	Compress   bool   `mapstructure:"compress"     default:"true"`
}

LogFileOptions configures a rotating log file output (lumberjack-backed). Empty path disables the entry; rotation thresholds are size-based with optional age/backup caps.

func (*LogFileOptions) Validate

func (f *LogFileOptions) Validate() error

type MetricsOptions

type MetricsOptions struct {
	Enabled bool   `mapstructure:"enabled" default:"true"`
	Path    string `mapstructure:"path"    default:"/metrics"`
}

MetricsOptions configures the /metrics (Prometheus) endpoint. Same auto-registration semantics as HealthOptions.

func (*MetricsOptions) Validate

func (o *MetricsOptions) Validate() error

type MySQLOptions

type MySQLOptions struct {
	Enabled         bool          `mapstructure:"enabled"            default:"true"`
	Host            string        `mapstructure:"host"               default:"127.0.0.1"`
	Port            int           `mapstructure:"port"               default:"3306"`
	Username        string        `mapstructure:"username"`
	Password        string        `mapstructure:"password"           sensitive:"true"`
	Database        string        `mapstructure:"database"`
	MaxOpenConns    int           `mapstructure:"max_open_conns"     default:"100"`
	MaxIdleConns    int           `mapstructure:"max_idle_conns"     default:"10"`
	ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"  default:"1h"`
	ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time" default:"10m"`
}

func (MySQLOptions) GoString

func (o MySQLOptions) GoString() string

GoString implements fmt.GoStringer for MySQLOptions. Prevents accidental credential leaks when using %#v.

func (MySQLOptions) String

func (o MySQLOptions) String() string

String implements fmt.Stringer for MySQLOptions.

func (*MySQLOptions) Validate

func (o *MySQLOptions) Validate() error

type RedisOptions

type RedisOptions struct {
	Enabled  bool   `mapstructure:"enabled"  default:"true"`
	Addr     string `mapstructure:"addr"     default:"127.0.0.1:6379"`
	Password string `mapstructure:"password"  sensitive:"true"`
	DB       int    `mapstructure:"db"       default:"0"`

	// Network timeouts. Defaults are tighter than go-redis' library
	// defaults (DialTimeout 5s, ReadTimeout 3s) because Redis on the hot
	// path of a web request should fail fast and let the caller fall back
	// (cache miss, circuit breaker) instead of stretching every request
	// to the library timeout.
	DialTimeout  time.Duration `mapstructure:"dial_timeout"  default:"1s"`
	ReadTimeout  time.Duration `mapstructure:"read_timeout"  default:"500ms"`
	WriteTimeout time.Duration `mapstructure:"write_timeout" default:"500ms"`
	PoolTimeout  time.Duration `mapstructure:"pool_timeout"  default:"1s"`
	PoolSize     int           `mapstructure:"pool_size"     default:"10"`
}

func (RedisOptions) GoString

func (o RedisOptions) GoString() string

GoString implements fmt.GoStringer for RedisOptions.

func (RedisOptions) String

func (o RedisOptions) String() string

String implements fmt.Stringer for RedisOptions.

func (*RedisOptions) Validate

func (o *RedisOptions) Validate() error

type SQLiteOptions

type SQLiteOptions struct {
	Enabled bool   `mapstructure:"enabled" default:"true"`
	Path    string `mapstructure:"path"    default:"app.db"`
}

func (*SQLiteOptions) Validate

func (o *SQLiteOptions) Validate() error

type SelfValidating

type SelfValidating interface {
	Validatable
	// contains filtered or unexported methods
}

SelfValidating signals that a Validatable type already validates its nested fields itself and the framework's recursive walker must NOT descend into them. Discriminator-shaped configs (e.g. DatabaseOptions where `driver: sqlite` selects between two mutually exclusive branches) implement this marker because blindly recursing would trip the validators on the *unselected* branch — those branches commonly have `enabled: true` defaults that demand fields the user deliberately left blank because they picked the other driver.

The interface intentionally has no methods; it is a pure type tag.

type SensitiveWarning

type SensitiveWarning struct {
	Path    string // e.g. "Account.SigningKey"
	EnvHint string // e.g. "MYAPP_ACCOUNT_SIGNING_KEY"
}

SensitiveWarning describes a sensitive config field that appears to hold a default / placeholder value rather than a real secret.

func AuditSensitiveDefaults

func AuditSensitiveDefaults(cfg any, envPrefix string) []SensitiveWarning

AuditSensitiveDefaults walks a config struct recursively and returns warnings for any field tagged sensitive:"true" whose value looks like a placeholder (contains "CHANGE", "TODO", "FIXME", "example", or is empty while the parent struct is enabled).

envPrefix is the application's environment variable prefix (e.g. "BLOG") so the warning can suggest the correct env var override.

type SlogOptions

type SlogOptions struct {
	Level  string           `mapstructure:"level"  default:"info"`
	Format string           `mapstructure:"format" default:"json"`
	Output []string         `mapstructure:"output" default:"stdout"`
	Files  []LogFileOptions `mapstructure:"files"`
	// AccessFiles, if non-empty, routes access-log entries (the ones written via
	// App.AccessLogger()) to a separate set of rotating files. Output is still
	// applied (stdout shows both streams) but app-log Files do NOT receive access
	// entries when this is set. Empty = access shares the main logger (legacy).
	AccessFiles []LogFileOptions `mapstructure:"access_files"`
	// AccessEnabled controls whether the application should record HTTP access
	// logs at all. Set false when a fronting proxy (nginx, traefik, etc.) already
	// captures access logs and you want to avoid double-logging. Application code
	// should consult App.AccessLogEnabled() before mounting the AccessLog
	// middleware. Default: true.
	AccessEnabled bool `mapstructure:"access_enabled" default:"true"`
}

func (*SlogOptions) Validate

func (o *SlogOptions) Validate() error

type SwaggerOptions

type SwaggerOptions struct {
	Enabled    bool   `mapstructure:"enabled"     default:"false"`
	Title      string `mapstructure:"title"`
	Version    string `mapstructure:"version"     default:"1.0.0"`
	Prefix     string `mapstructure:"prefix"      default:"/swagger"`
	BearerAuth bool   `mapstructure:"bearer_auth" default:"true"`
}

type Validatable

type Validatable interface {
	Validate() error
}

Validatable is implemented by config structs that need validation. Run() calls Validate() on each sub-Options after unmarshal, then on the root config if it implements Validatable.

Jump to

Keyboard shortcuts

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