feat(config): add database secret file and session TTL settings

This commit is contained in:
kk10
2026-10-03 12:32:09 +03:00
parent 4c1d08f8a8
commit 60fad0fca7
2 changed files with 51 additions and 8 deletions
+1 -6
View File
@@ -1,15 +1,10 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0
APP_PORT=8080
APP_ENV=lab
MAX_INFLIGHT_REQUESTS=0
SESSION_TTL_SECONDS=3600
LOG_LEVEL=INFO
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
+50 -2
View File
@@ -1,40 +1,59 @@
package config
import (
"fmt"
"log"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Server ServerConfig
Logging LoggingConfig
Server ServerConfig
Logging LoggingConfig
Database DatabaseConfig
}
type ServerConfig struct {
Host string
Port string
MaxInflightRequests int
SessionTTL time.Duration
}
type LoggingConfig struct {
Level slog.Level
}
type DatabaseConfig struct {
URLFile string
}
func (c DatabaseConfig) URL() (string, error) {
return readSecretFile(c.URLFile)
}
func Load() Config {
return Config{
Server: ServerConfig{
Host: getEnv("APP_HOST", "0.0.0.0"),
Port: getEnv("APP_PORT", "8080"),
MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0),
SessionTTL: time.Duration(getEnvPositiveInt("SESSION_TTL_SECONDS", 3600)) * time.Second,
},
Logging: LoggingConfig{
Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo),
},
Database: DatabaseConfig{
URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"),
},
}
}
func getEnv(key, def string) string {
value := os.Getenv(key)
if value == "" {
@@ -59,6 +78,21 @@ func getEnvNonNegativeInt(key string, def int) int {
return value
}
func getEnvPositiveInt(key string, def int) int {
v := os.Getenv(key)
if v == "" {
return def
}
value, err := strconv.Atoi(v)
if err != nil || value <= 0 {
log.Printf("invalid positive int for %s=%q, using default %d", key, v, def)
return def
}
return value
}
func getEnvLogLevel(key string, def slog.Level) slog.Level {
v := os.Getenv(key)
@@ -78,3 +112,17 @@ func getEnvLogLevel(key string, def slog.Level) slog.Level {
return def
}
}
func readSecretFile(path string) (string, error) {
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read secret file %s: %w", path, err)
}
value := strings.TrimSpace(string(b))
if value == "" {
return "", fmt.Errorf("secret file %s is empty", path)
}
return value, nil
}