Files
mtusi2026lab2/internal/config/config.go
T

68 lines
1.6 KiB
Go

package config
import (
"fmt"
"net"
"os"
"strconv"
"time"
)
// Config - параметры процесса.
type Config struct {
Host string
Port string
Env string
ShutdownTimeout time.Duration
}
// Addr — адрес прослушивания. В контейнере это 0.0.0.0:8080,
// иначе published port Docker не попадёт в процесс.
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, c.Port)
}
// Load завершает запуск ошибкой, если значение вне допустимого диапазона.
func Load() (Config, error) {
var c Config
c.Host = getenv("APP_HOST", "0.0.0.0")
c.Port = getenv("APP_PORT", "8080")
c.Env = getenv("APP_ENV", "lab")
if c.Host == "" {
return Config{}, fmt.Errorf("APP_HOST is empty")
}
port, err := strconv.Atoi(c.Port)
if err != nil || port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT must be 1..65535")
}
sec, err := nonNeg("SHUTDOWN_TIMEOUT_SECONDS", 8)
if err != nil {
return Config{}, err
}
if sec < 1 || sec > 10 {
return Config{}, fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..10")
}
c.ShutdownTimeout = time.Duration(sec) * time.Second
return c, nil
}
func getenv(key, def string) string {
if v, ok := os.LookupEnv(key); ok && v != "" {
return v
}
return def
}
func nonNeg(key string, def int) (int, error) {
v, ok := os.LookupEnv(key)
if !ok || v == "" {
return def, nil
}
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
return 0, fmt.Errorf("%s must be a non-negative integer", key)
}
return n, nil
}