Files
MarketGrid/xyzserver/config.go
T

102 lines
2.3 KiB
Go

package main
import (
"fmt"
"net"
"os"
"strconv"
"time"
)
const (
retainDuration = 72 * time.Hour
flushEvery = 10 * time.Second
onlineRefreshEvery = 30 * time.Second
cleanupEvery = time.Hour
summaryEvery = 10 * time.Minute
rangeSlack = 5 * time.Minute
shutdownFor = 10 * time.Second
cookieMaxAge = 31536000
uaMaxBytes = 256
)
// Config 来自环境变量。非法值直接失败,不回退到默认值。
type Config struct {
Listen string
DataDir string
OnlineMinutes int
TrustProxy bool
HTTPSOnly bool
TLSCert string
TLSKey string
DebugLog bool
}
func loadConfig() (Config, error) {
cfg := Config{
Listen: "127.0.0.1:8080",
DataDir: "./data",
OnlineMinutes: 15,
}
if v, ok := os.LookupEnv("XYZ_LISTEN"); ok {
if _, _, err := net.SplitHostPort(v); err != nil {
return Config{}, fmt.Errorf("XYZ_LISTEN 无效: %q", v)
}
cfg.Listen = v
}
if v, ok := os.LookupEnv("XYZ_DATA_DIR"); ok {
if v == "" {
return Config{}, fmt.Errorf("XYZ_DATA_DIR 不能为空")
}
cfg.DataDir = v
}
if v, ok := os.LookupEnv("XYZ_ONLINE_MINUTES"); ok {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > 120 {
return Config{}, fmt.Errorf("XYZ_ONLINE_MINUTES 必须是 1 到 120 的整数")
}
cfg.OnlineMinutes = n
}
if v, ok := os.LookupEnv("XYZ_TRUST_PROXY"); ok {
switch v {
case "true":
cfg.TrustProxy = true
case "false":
cfg.TrustProxy = false
default:
return Config{}, fmt.Errorf("XYZ_TRUST_PROXY 必须是 true 或 false")
}
}
if v, ok := os.LookupEnv("XYZ_COUNT_HTTPS_ONLY"); ok {
switch v {
case "true":
cfg.HTTPSOnly = true
case "false":
cfg.HTTPSOnly = false
default:
return Config{}, fmt.Errorf("XYZ_COUNT_HTTPS_ONLY 必须是 true 或 false")
}
}
cert, hasCert := os.LookupEnv("XYZ_TLS_CERT")
key, hasKey := os.LookupEnv("XYZ_TLS_KEY")
if hasCert || hasKey {
if cert == "" || key == "" {
return Config{}, fmt.Errorf("XYZ_TLS_CERT 和 XYZ_TLS_KEY 必须同时设置")
}
cfg.TLSCert = cert
cfg.TLSKey = key
}
if v, ok := os.LookupEnv("XYZ_DEBUG_LOG"); ok {
switch v {
case "1":
cfg.DebugLog = true
case "0":
cfg.DebugLog = false
default:
return Config{}, fmt.Errorf("XYZ_DEBUG_LOG 必须是 0 或 1")
}
}
return cfg, nil
}