forked from mtusi2026/mtusi2026lab4
feat: lab4 - S3 attachments, image validation, failover
This commit is contained in:
+49
-14
@@ -1,27 +1,62 @@
|
||||
// Package config reads the runtime configuration shared by every API replica.
|
||||
package config
|
||||
|
||||
import "os"
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPort = "8080"
|
||||
defaultSessionTTL = time.Hour
|
||||
defaultIdempotencyTTL = 24 * time.Hour
|
||||
defaultDrainDelay = 3 * time.Second
|
||||
)
|
||||
|
||||
// Config is the complete runtime configuration of one API process.
|
||||
type Config struct {
|
||||
InstanceID string
|
||||
Port string
|
||||
DatabaseURL string
|
||||
InstanceID string
|
||||
Port string
|
||||
DatabaseURL string
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
DrainDelay time.Duration
|
||||
}
|
||||
|
||||
// Load reads the environment; DATABASE_URL is the only mandatory value.
|
||||
func Load() *Config {
|
||||
cfg := &Config{
|
||||
InstanceID: os.Getenv("APP_INSTANCE_ID"),
|
||||
Port: os.Getenv("APP_PORT"),
|
||||
DatabaseURL: os.Getenv("DATABASE_URL"),
|
||||
}
|
||||
if cfg.InstanceID == "" {
|
||||
cfg.InstanceID = "api"
|
||||
}
|
||||
if cfg.Port == "" {
|
||||
cfg.Port = "8080"
|
||||
InstanceID: valueOr(os.Getenv("APP_INSTANCE_ID"), "api"),
|
||||
Port: valueOr(os.Getenv("APP_PORT"), defaultPort),
|
||||
DatabaseURL: os.Getenv("DATABASE_URL"),
|
||||
SessionTTL: durationOr("SESSION_TTL_SECONDS", defaultSessionTTL),
|
||||
IdempotencyTTL: durationOr("IDEMPOTENCY_TTL_SECONDS", defaultIdempotencyTTL),
|
||||
DrainDelay: durationOr("DRAIN_DELAY_SECONDS", defaultDrainDelay),
|
||||
}
|
||||
if cfg.DatabaseURL == "" {
|
||||
panic("APP_INSTANCE_ID/APP_PORT optional; DATABASE_URL is required")
|
||||
log.Fatal("config: DATABASE_URL is required")
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func valueOr(raw, fallback string) string {
|
||||
if raw == "" {
|
||||
return fallback
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func durationOr(env string, fallback time.Duration) time.Duration {
|
||||
raw := os.Getenv(env)
|
||||
if raw == "" {
|
||||
return fallback
|
||||
}
|
||||
seconds, err := strconv.Atoi(raw)
|
||||
if err != nil || seconds <= 0 {
|
||||
log.Printf("config: ignoring invalid %s=%q, using %s", env, raw, fallback)
|
||||
return fallback
|
||||
}
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user