Documentation
¶
Overview ¶
Package config provides application configuration loaded from environment variables.
Role in architecture:
- Infrastructure: reads from OS environment and optional .env file (via godotenv).
- Single source of truth for server, database, Redis, GCS, rate limiter, CORS, and timezone settings.
Responsibilities:
- Load and parse environment variables into typed structs (Configuration and nested types).
- Server includes JWT settings: algorithm (default RS256), key paths or Secret Manager names, issuer, audience, key ID.
- Validate required database configuration (Dbname, Username, Password; CloudSQLInstance when driver is cloudsql-*).
- Expose global configuration via GetConfig(); lazy-build from env when Config is nil.
- Strip surrounding quotes from env values; treat known placeholders as invalid.
Constraints:
- No file-based config formats (YAML/JSON) except .env for variable loading.
- No secret injection from external secret managers; callers must set env before Setup/GetConfig.
- Database validation runs only for primary and (if Dbname set) site database; other sections are not validated.
This package must NOT:
- Perform I/O beyond reading environment and loading a single .env file.
- Depend on database, Redis, or HTTP packages.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Setup ¶
Setup loads configuration from the environment and validates required database settings.
If configPath is non-empty, godotenv loads that file (e.g. ".env"); otherwise godotenv.Load() is used (current directory .env). After loading, buildConfigFromEnv reads all supported variables and validateDatabaseConfig is run for the primary database and, if DatabaseSite.Dbname is set, for the site database.
Setup returns an error if database validation fails (missing Dbname, Username, Password, or CloudSQLInstance when driver is cloudsql-mysql/cloudsql-postgres).
Types ¶
type Configuration ¶
type Configuration struct {
Server ServerConfiguration
Cors CorsConfiguration
Database DatabaseConfiguration
DatabaseSite DatabaseConfiguration // Optional second database; leave Dbname empty to disable.
Redis RedisConfiguration
GCS GCSConfiguration
RateLimiter RateLimiterConfiguration
Timezone TimezoneConfiguration
}
Configuration holds the full application configuration. All sections are populated from environment variables by buildConfigFromEnv (see parser.go).
var Config *Configuration
Config holds the global configuration instance. It is set by Setup or lazily built from environment variables by GetConfig. Tests may set it directly.
func GetConfig ¶
func GetConfig() *Configuration
GetConfig returns the global configuration. If Config is nil, it builds configuration from the current environment via buildConfigFromEnv and assigns it to Config. No validation is performed on this path; call Setup at startup for validation.
type CorsConfiguration ¶
type CorsConfiguration struct {
Global bool // If true, allow all origins
Ips string // Comma-separated allowed IPs when Global is false
}
CorsConfiguration holds CORS settings. Global true allows all origins; Ips is used when Global is false.
type DatabaseConfiguration ¶
type DatabaseConfiguration struct {
Driver string
Dbname string
Username string
Password string
Host string
Port string
Sslmode bool
Logmode bool
CloudSQLInstance string `mapstructure:"cloud_sql_instance"` // project:region:instance for Cloud SQL
MaxIdleConns int // 0 = default 5
MaxOpenConns int // 0 = default 10
ConnMaxLifetimeMinutes int // 0 = default 1440 (24h)
}
DatabaseConfiguration holds database connection and pool settings. Required: Dbname, Username, Password. For Cloud SQL drivers (cloudsql-mysql, cloudsql-postgres), CloudSQLInstance (project:region:instance) is required.
type GCSConfiguration ¶
type GCSConfiguration struct {
Enabled bool
BucketName string
CredentialsFile string // Optional; omit to use Application Default Credentials
}
GCSConfiguration holds Google Cloud Storage settings. BucketName required when Enabled is true.
type RateLimiterConfiguration ¶ added in v0.1.7
type RateLimiterConfiguration struct {
Enabled bool
Requests int // Max requests per window
Window int // Window size in seconds
KeyBy string // "ip" or "user" (user requires auth middleware)
SkipPaths string // Comma-separated paths to skip (e.g. "/health,/metrics")
}
RateLimiterConfiguration holds rate limiter settings. Requires Redis when Enabled is true.
type RedisConfiguration ¶
type RedisConfiguration struct {
Enabled bool
Host string
Port string
Password string
DB int // Database index; ignored in cluster mode
ClusterMode bool // Use cluster client (e.g. Google Cloud Memorystore)
ClusterNodes string // Comma-separated host:port when ClusterMode is true
PoolSize int // 0 = client default; use e.g. 100 for high RPS
MinIdleConns int // 0 = default
ReadTimeoutSec int // 0 = no timeout
WriteTimeoutSec int // 0 = no timeout
}
RedisConfiguration holds Redis connection and pool settings. Set Enabled true to use Redis.
type ServerConfiguration ¶
type ServerConfiguration struct {
Port string // Listen port; default "8080"
Secret string // JWT signing secret (used when JWTSigningAlgorithm is HS256)
Mode string // Gin mode: "debug", "release", "test"
AccessTokenExpiry int // Access token lifetime in hours
RefreshTokenExpiry int // Refresh token lifetime in days
SessionExpiry int // Session lifetime in hours; default 24
SessionCookieName string
SessionSecure bool // Secure flag for cookies (HTTPS only)
SessionHttpOnly bool // HttpOnly flag; default true
SessionSameSite string // "strict", "lax", or "none"
// JWT asymmetric signing: "HS256" (default), "RS256", or "ES256"
JWTSigningAlgorithm string // When RS256/ES256, use key paths/PEM or embedded PEM (JWTPrivateKeyPEM/JWTPublicKeyPEM)
JWTPrivateKey string // PEM private key: file path, or inline PEM (value contains -----BEGIN); ignored if JWTPrivateKeyPEM is set
JWTPublicKey string // PEM public key: file path, or inline PEM; ignored if JWTPublicKeyPEM is set
// JWT keys from embed or in-memory PEM (optional). When set, used instead of JWTPrivateKey/JWTPublicKey.
// Example: cfg.Server.JWTPrivateKeyPEM = keys.PrivateKey after //go:embed keys/private.pem
JWTPrivateKeyPEM []byte
JWTPublicKeyPEM []byte
// JWT claims: issuer (iss), audience (aud), and key ID (kid) in header
JWTIssuer string // Issuer (iss); optional
JWTAudience string // Audience (aud); optional, comma-separated for multiple
JWTKeyID string // Key ID (kid) in JWT header; optional, for key rotation
}
ServerConfiguration holds server and session settings (port, secret, mode, token and session expiry).
type TimezoneConfiguration ¶ added in v0.1.7
type TimezoneConfiguration struct {
Timezone string
}
TimezoneConfiguration holds the server timezone (IANA name, e.g. "Asia/Jakarta", "UTC").