Files
2026-10-06 22:45:35 +03:00

101 lines
2.4 KiB
Go

package config
import (
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Port string
PostgresHost string
PostgresPort uint16
PostgresUser string
PostgresDatabase string
PostgresPassword string
PostgresMaxConns int32
RedisAddr string
SessionTTL time.Duration
QueryTimeout time.Duration
CursorKey [32]byte
}
func value(name, fallback string) string {
if v := os.Getenv(name); v != "" {
return v
}
return fallback
}
func positive(name string, fallback, max int) (int, error) {
n, err := strconv.Atoi(value(name, strconv.Itoa(fallback)))
if err != nil || n < 1 || n > max {
return 0, fmt.Errorf("invalid %s", name)
}
return n, nil
}
func secret(name string) (string, error) {
if file := os.Getenv(name + "_FILE"); file != "" {
data, err := os.ReadFile(file)
if err != nil {
return "", fmt.Errorf("cannot read %s_FILE", name)
}
if s := strings.TrimSpace(string(data)); s != "" {
return s, nil
}
}
if s := os.Getenv(name); s != "" {
return s, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func Load() (Config, error) {
var c Config
port, err := positive("PORT", 8080, 65535)
if err != nil {
return c, err
}
c.Port = strconv.Itoa(port)
pgPort, err := positive("POSTGRES_PORT", 5432, 65535)
if err != nil {
return c, err
}
c.PostgresPort = uint16(pgPort)
max, err := positive("POSTGRES_MAX_CONNS", 10, 100)
if err != nil {
return c, err
}
c.PostgresMaxConns = int32(max)
ttl, err := positive("SESSION_TTL_SECONDS", 3600, 86400*30)
if err != nil {
return c, err
}
c.SessionTTL = time.Duration(ttl) * time.Second
timeout, err := positive("QUERY_TIMEOUT_MS", 2000, 10000)
if err != nil {
return c, err
}
c.QueryTimeout = time.Duration(timeout) * time.Millisecond
c.PostgresHost = value("POSTGRES_HOST", "localhost")
c.PostgresUser = value("POSTGRES_USER", "messenger")
c.PostgresDatabase = value("POSTGRES_DB", "messenger")
c.RedisAddr = value("REDIS_ADDR", "localhost:6379")
c.PostgresPassword, err = secret("POSTGRES_PASSWORD")
if err != nil {
return c, err
}
key, err := secret("CURSOR_KEY")
if err != nil {
return c, err
}
decoded, err := hex.DecodeString(key)
if err != nil || len(decoded) != 32 {
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
}
copy(c.CursorKey[:], decoded)
return c, nil
}