config

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package config provides a lightweight, type-safe configuration layer for serverless and HTTP services. It exposes generic, domain-agnostic configuration types plus validation and DSN helpers.

The "env" struct tags carry generic, prefix-less variable names (for example "DB_WRITE_HOST"). Consuming services own the project-specific environment prefix (for example "MYAPP_") and prepend it when binding environment variables, so no project naming lives in this module.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyReadDatabaseFallback added in v0.1.3

func ApplyReadDatabaseFallback(write WriteDatabaseConfig, read *ReadDatabaseConfig)

ApplyReadDatabaseFallback copies the write-database settings into read when no read host is configured. This is convenient for local and test environments that run a single PostgreSQL instance with no dedicated read replica.

It operates on the building-block database configs (rather than a whole Config) so it composes with any configuration layout — whether a service embeds the shared Config or declares its own database fields of these types.

func ApplySecrets

func ApplySecrets(ctx context.Context, cfg *Config, provider SecretsProvider) error

ApplySecrets applies secrets from a provider to the configuration. This is called after loading config to populate sensitive fields from a secrets manager.

The function retrieves all secrets from the provider and maps them to config fields:

  • db_write_password -> WriteDatabase.Password
  • db_read_password -> ReadDatabase.Password

If a secret is not found in the provider, the existing config value is preserved.

func LoadFromEnv added in v0.1.3

func LoadFromEnv(cfg any, prefix string, opts ...Option) error

LoadFromEnv applies environment-variable overrides to cfg, which must be a non-nil pointer to a struct.

For every field carrying a tag of the form `env:"NAME"`, the loader reads os.Getenv(prefix+NAME); when that value is non-empty it is parsed and assigned to the field. The prefix lets each consuming service own its environment namespace (for example "MYAPP_") while the shared config types keep generic, prefix-less tags. Nested structs — including anonymous embedded ones — are walked recursively, so a service that embeds config.Config binds the shared fields and its own fields in a single call.

Supported field kinds: string, bool, all sized int/uint and float kinds, time.Duration ("30s"), []string (comma-separated), and any type whose pointer implements encoding.TextUnmarshaler. Unexported fields and unsupported kinds are skipped.

By default the loader is lenient: a value that fails to parse is logged and the field keeps its prior value (typically the JSON default). WithStrict makes such failures return a joined error instead.

Types

type AWSConfig

type AWSConfig struct {
	Region string `json:"region" env:"AWS_REGION"`
}

AWSConfig contains AWS-specific configuration.

func (*AWSConfig) Validate

func (a *AWSConfig) Validate() error

Validate validates the AWSConfig and returns an error if invalid.

type ApplicationConfig

type ApplicationConfig struct {
	Name        string `json:"name" env:"APP_NAME"`
	Version     string `json:"version" env:"APP_VERSION"`
	Commit      string `json:"commit" env:"APP_COMMIT"`
	Environment string `json:"environment"`
	Debug       bool   `json:"debug" env:"APP_DEBUG"`
	Timeout     int    `json:"timeout" env:"APP_TIMEOUT"`
}

ApplicationConfig contains application-level settings.

func (*ApplicationConfig) Validate

func (a *ApplicationConfig) Validate() error

Validate validates the ApplicationConfig and returns an error if invalid.

type Config

type Config struct {
	Environment   string              `json:"environment"`
	Application   ApplicationConfig   `json:"application"`
	WriteDatabase WriteDatabaseConfig `json:"write_database"`
	ReadDatabase  ReadDatabaseConfig  `json:"read_database"`
	Logging       LoggingConfig       `json:"logging"`
	AWS           AWSConfig           `json:"aws"`
}

Config is the root configuration structure containing all generic application settings. Services that need additional, project-specific configuration embed this type and add their own fields.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the entire Config structure and all nested configurations. All validation errors are collected and returned together via errors.Join so operators can fix every issue in one pass rather than one at a time.

type DatabaseConfig

type DatabaseConfig interface {
	ConnectionString() string
	GetHost() string
	GetPort() int
	GetDatabase() string
	GetUsername() string
	GetPassword() string
	GetSSLMode() string
	GetMaxOpenConns() int
	GetMaxIdleConns() int
	GetConnMaxLifetime() int
	GetDriver() string
}

DatabaseConfig is a common interface for database configuration. Both WriteDatabaseConfig and ReadDatabaseConfig implement this through their methods.

type LoggingConfig

type LoggingConfig struct {
	Level            string `json:"level" env:"LOG_LEVEL"`
	Format           string `json:"format" env:"LOG_FORMAT"`
	IncludeTimestamp bool   `json:"include_timestamp" env:"LOG_INCLUDE_TIMESTAMP"`
	IncludeCaller    bool   `json:"include_caller" env:"LOG_INCLUDE_CALLER"`
}

LoggingConfig contains logging configuration for structured JSON logging.

func (*LoggingConfig) Validate

func (l *LoggingConfig) Validate() error

Validate validates the LoggingConfig and returns an error if invalid.

type Option added in v0.1.3

type Option func(*loadOptions)

Option customizes LoadFromEnv behavior.

func WithLogger added in v0.1.3

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger used to report ignored, malformed values in the default (lenient) mode. When nil, slog.Default() is used.

func WithStrict added in v0.1.3

func WithStrict() Option

WithStrict makes LoadFromEnv return an error for every malformed value rather than logging it and keeping the field's existing value. Use it on hosts that should fail fast at startup on a bad environment variable.

func WithTag added in v0.1.3

func WithTag(tag string) Option

WithTag overrides the struct tag key that carries the environment variable name. The default is "env".

type ReadDatabaseConfig

type ReadDatabaseConfig struct {
	Host            string `json:"host" env:"DB_READ_HOST"`
	Port            int    `json:"port" env:"DB_READ_PORT"`
	Database        string `json:"database" env:"DB_READ_NAME"`
	Username        string `json:"username" env:"DB_READ_USERNAME"`
	Password        string `json:"password" env:"DB_READ_PASSWORD"`
	SSLMode         string `json:"ssl_mode" env:"DB_READ_SSL_MODE"`
	MaxOpenConns    int    `json:"max_open_conns" env:"DB_READ_MAX_OPEN_CONNS"`
	MaxIdleConns    int    `json:"max_idle_conns" env:"DB_READ_MAX_IDLE_CONNS"`
	ConnMaxLifetime int    `json:"conn_max_lifetime" env:"DB_READ_CONN_MAX_LIFETIME"`
	Driver          string `json:"driver" env:"DB_READ_DRIVER"`
}

ReadDatabaseConfig contains database connection configuration for the read replica PostgreSQL instance.

func (*ReadDatabaseConfig) ConnMaxLifetimeDuration

func (d *ReadDatabaseConfig) ConnMaxLifetimeDuration() time.Duration

ConnMaxLifetimeDuration returns the connection max lifetime as a time.Duration.

func (*ReadDatabaseConfig) ConnectionString

func (d *ReadDatabaseConfig) ConnectionString() string

ConnectionString builds a PostgreSQL connection string from ReadDatabaseConfig. Returns a DSN suitable for use with pgx driver.

func (*ReadDatabaseConfig) GetConnMaxLifetime

func (d *ReadDatabaseConfig) GetConnMaxLifetime() int

GetConnMaxLifetime returns the connection maximum lifetime in minutes.

func (*ReadDatabaseConfig) GetDatabase

func (d *ReadDatabaseConfig) GetDatabase() string

GetDatabase returns the database name.

func (*ReadDatabaseConfig) GetDriver

func (d *ReadDatabaseConfig) GetDriver() string

GetDriver returns the database driver name.

func (*ReadDatabaseConfig) GetHost

func (d *ReadDatabaseConfig) GetHost() string

GetHost returns the database host.

func (*ReadDatabaseConfig) GetMaxIdleConns

func (d *ReadDatabaseConfig) GetMaxIdleConns() int

GetMaxIdleConns returns the maximum number of idle connections.

func (*ReadDatabaseConfig) GetMaxOpenConns

func (d *ReadDatabaseConfig) GetMaxOpenConns() int

GetMaxOpenConns returns the maximum number of open connections.

func (*ReadDatabaseConfig) GetPassword

func (d *ReadDatabaseConfig) GetPassword() string

GetPassword returns the database password.

func (*ReadDatabaseConfig) GetPort

func (d *ReadDatabaseConfig) GetPort() int

GetPort returns the database port.

func (*ReadDatabaseConfig) GetSSLMode

func (d *ReadDatabaseConfig) GetSSLMode() string

GetSSLMode returns the SSL mode.

func (*ReadDatabaseConfig) GetUsername

func (d *ReadDatabaseConfig) GetUsername() string

GetUsername returns the database username.

func (*ReadDatabaseConfig) Validate

func (d *ReadDatabaseConfig) Validate() error

Validate validates the ReadDatabaseConfig and returns an error if invalid.

type SecretsProvider

type SecretsProvider interface {
	GetSecret(ctx context.Context, key string) (string, error)
	GetAllSecrets(ctx context.Context) (map[string]string, error)
}

SecretsProvider is the interface for retrieving secrets. It mirrors the provider interface exposed by the secrets package and is declared here to avoid an import cycle.

type WriteDatabaseConfig

type WriteDatabaseConfig struct {
	Host            string `json:"host" env:"DB_WRITE_HOST"`
	Port            int    `json:"port" env:"DB_WRITE_PORT"`
	Database        string `json:"database" env:"DB_WRITE_NAME"`
	Username        string `json:"username" env:"DB_WRITE_USERNAME"`
	Password        string `json:"password" env:"DB_WRITE_PASSWORD"`
	SSLMode         string `json:"ssl_mode" env:"DB_WRITE_SSL_MODE"`
	MaxOpenConns    int    `json:"max_open_conns" env:"DB_WRITE_MAX_OPEN_CONNS"`
	MaxIdleConns    int    `json:"max_idle_conns" env:"DB_WRITE_MAX_IDLE_CONNS"`
	ConnMaxLifetime int    `json:"conn_max_lifetime" env:"DB_WRITE_CONN_MAX_LIFETIME"`
	Driver          string `json:"driver" env:"DB_WRITE_DRIVER"`
}

WriteDatabaseConfig contains database connection configuration for the primary/write PostgreSQL instance.

func (*WriteDatabaseConfig) ConnMaxLifetimeDuration

func (d *WriteDatabaseConfig) ConnMaxLifetimeDuration() time.Duration

ConnMaxLifetimeDuration returns the connection max lifetime as a time.Duration.

func (*WriteDatabaseConfig) ConnectionString

func (d *WriteDatabaseConfig) ConnectionString() string

ConnectionString builds a PostgreSQL connection string from WriteDatabaseConfig. Returns a DSN suitable for use with pgx driver.

func (*WriteDatabaseConfig) GetConnMaxLifetime

func (d *WriteDatabaseConfig) GetConnMaxLifetime() int

GetConnMaxLifetime returns the connection maximum lifetime in minutes.

func (*WriteDatabaseConfig) GetDatabase

func (d *WriteDatabaseConfig) GetDatabase() string

GetDatabase returns the database name.

func (*WriteDatabaseConfig) GetDriver

func (d *WriteDatabaseConfig) GetDriver() string

GetDriver returns the database driver name.

func (*WriteDatabaseConfig) GetHost

func (d *WriteDatabaseConfig) GetHost() string

GetHost returns the database host.

func (*WriteDatabaseConfig) GetMaxIdleConns

func (d *WriteDatabaseConfig) GetMaxIdleConns() int

GetMaxIdleConns returns the maximum number of idle connections.

func (*WriteDatabaseConfig) GetMaxOpenConns

func (d *WriteDatabaseConfig) GetMaxOpenConns() int

GetMaxOpenConns returns the maximum number of open connections.

func (*WriteDatabaseConfig) GetPassword

func (d *WriteDatabaseConfig) GetPassword() string

GetPassword returns the database password.

func (*WriteDatabaseConfig) GetPort

func (d *WriteDatabaseConfig) GetPort() int

GetPort returns the database port.

func (*WriteDatabaseConfig) GetSSLMode

func (d *WriteDatabaseConfig) GetSSLMode() string

GetSSLMode returns the SSL mode.

func (*WriteDatabaseConfig) GetUsername

func (d *WriteDatabaseConfig) GetUsername() string

GetUsername returns the database username.

func (*WriteDatabaseConfig) Validate

func (d *WriteDatabaseConfig) Validate() error

Validate validates the WriteDatabaseConfig and returns an error if invalid.

Jump to

Keyboard shortcuts

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