Files
mtusi2026lab2-implementation/internal/config/config.go
T

61 lines
1.3 KiB
Go

package config
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Host string
Port string
Env string
SessionTTL time.Duration
DatabaseURL string
CacheURL string
}
func Load() (Config, error) {
ttl, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
if err != nil || ttl <= 0 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
}
databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url")
if err != nil {
return Config{}, err
}
cacheURL, err := readSecret("CACHE_URL_FILE", "/run/secrets/cache_url")
if err != nil {
return Config{}, err
}
return Config{
Host: getenv("APP_HOST", "0.0.0.0"),
Port: getenv("APP_PORT", "8080"),
Env: getenv("APP_ENV", "lab"),
SessionTTL: time.Duration(ttl) * time.Second,
DatabaseURL: databaseURL,
CacheURL: cacheURL,
}, nil
}
func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) }
func readSecret(key, def string) (string, error) {
path := getenv(key, def)
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s: cannot read %s", key, path)
}
return strings.TrimSpace(string(b)), nil
}
func getenv(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}