MWSE/internal/config/config.go

72 lines
1.9 KiB
Go

// Package config loads engine settings from the environment, replacing the
// hard-coded values in the original config.js / HTTPServer.js.
package config
import (
"net"
"os"
"strconv"
"time"
)
// Config holds all runtime settings.
type Config struct {
Host string // bind address, e.g. "0.0.0.0"
Port int // listen port, default 7707
PublicDir string // static assets directory (default "./public")
ScriptDir string // built SDK directory (default "./script")
ReadHeaderTimeout time.Duration // HTTP read-header timeout
ShutdownTimeout time.Duration // grace period for in-flight work on shutdown
TermOutput bool // verbose terminal logging (the old `termoutput` flag)
}
// Load reads configuration from the environment, applying defaults that match the
// original server. Recognised variables:
//
// MWSE_HOST, MWSE_PORT, MWSE_PUBLIC_DIR, MWSE_SCRIPT_DIR,
// MWSE_SHUTDOWN_TIMEOUT (seconds), MWSE_TERM_OUTPUT (1/true)
func Load() Config {
return Config{
Host: env("MWSE_HOST", "0.0.0.0"),
Port: envInt("MWSE_PORT", 7707),
PublicDir: env("MWSE_PUBLIC_DIR", "./public"),
ScriptDir: env("MWSE_SCRIPT_DIR", "./script"),
ReadHeaderTimeout: 10 * time.Second,
ShutdownTimeout: time.Duration(envInt("MWSE_SHUTDOWN_TIMEOUT", 10)) * time.Second,
TermOutput: envBool("MWSE_TERM_OUTPUT", false),
}
}
// Addr returns the host:port string for net/http.
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
}
func env(key, def string) string {
if v, ok := os.LookupEnv(key); ok && v != "" {
return v
}
return def
}
func envInt(key string, def int) int {
if v, ok := os.LookupEnv(key); ok {
if n, err := strconv.Atoi(v); err == nil {
return n
}
}
return def
}
func envBool(key string, def bool) bool {
if v, ok := os.LookupEnv(key); ok {
if b, err := strconv.ParseBool(v); err == nil {
return b
}
}
return def
}