diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..2b53320 --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,75 @@ +package config + +import ( + "fmt" + "os" + "strconv" + "strings" + "time" +) + +type Config struct { + Host string + Port string + DatabaseURL string + SessionTTL time.Duration +} + +func Load() (*Config, error) { + dsn, err := readSecret("DATABASE_URL_FILE", "DATABASE_URL") + if err != nil { + return nil, fmt.Errorf("database url: %w", err) + } + + ttlSeconds, err := readInt("SESSION_TTL_SECONDS", 3600) + if err != nil { + return nil, fmt.Errorf("SESSION_TTL_SECONDS: %w", err) + } + if ttlSeconds <= 0 { + return nil, fmt.Errorf("SESSION_TTL_SECONDS должен быть положительным") + } + + return &Config{ + Host: getenv("APP_HOST", "0.0.0.0"), + Port: getenv("APP_PORT", "8080"), + DatabaseURL: dsn, + SessionTTL: time.Duration(ttlSeconds) * time.Second, + }, nil +} + +func getenv(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} + +func readInt(key string, def int) (int, error) { + v := os.Getenv(key) + if v == "" { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil { + return 0, fmt.Errorf("не целое число: %q", v) + } + return n, nil +} + +func readSecret(fileEnv, envKey string) (string, error) { + if path := os.Getenv(fileEnv); path != "" { + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("чтение %s=%s: %w", fileEnv, path, err) + } + s := strings.TrimSpace(string(b)) + if s == "" { + return "", fmt.Errorf("файл %s пуст", path) + } + return s, nil + } + if v := os.Getenv(envKey); v != "" { + return v, nil + } + return "", fmt.Errorf("не задан %s или %s", fileEnv, envKey) +}