sky/internal/platform/config/config.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

159 lines
4.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// Config 全部配置来自环境变量,无配置文件依赖。
// 生产环境由 K8s ConfigMap/Secret 或 systemd EnvironmentFile 注入。
type Config struct {
Env string // dev | prod
HTTPAddr string
PGDSN string
PGMaxConns int32
ValKeyAddr string
ValKeyPass string
ValKeyDB int
JWTSecret []byte
JWTTTL time.Duration
// SessionRenewLast 滑动续约窗口:会话剩余有效期低于该值时,
// 下次命中自动续回满 JWTTTL;活跃用户约每 (JWTTTL-窗口) 续一次。
// 取值 <=0 或 >= JWTTTL 时视为关闭续约(纯绝对过期)。
SessionRenewLast time.Duration
S3 S3Config
RateLimit RateLimitConfig
// OTLPEnabledpoint 为空则把 span 打到 stdout(本地开发);
// 生产填 otel-collector:4317 之类的 gRPC 端点
OTLPEnabledpoint string
TraceSampleRatio float64
// CORSOrigins 允许跨域的来源白名单。生产必须显式配置,
// 开发模式额外放行本机任意端口(前端 dev server 端口会变)。
CORSOrigins []string
}
type S3Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
PublicBase string // CDN 域名,用于拼接最终 URL
}
type RateLimitConfig struct {
AnonPerMinute int
UserPerMinute int
}
func loadDotEnv() {
data, err := os.ReadFile(".env")
if err != nil {
return
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
k := strings.TrimSpace(parts[0])
v := strings.TrimSpace(parts[1])
v = strings.Trim(v, "\r\"'")
if os.Getenv(k) == "" {
_ = os.Setenv(k, v)
}
}
}
}
func Load() (*Config, error) {
loadDotEnv()
c := &Config{
Env: env("APP_ENV", "dev"),
HTTPAddr: env("HTTP_ADDR", ":8080"),
PGDSN: env("PG_DSN", ""),
PGMaxConns: int32(envInt("PG_MAX_CONNS", 20)),
ValKeyAddr: env("VALKEY_ADDR", "127.0.0.1:6379"),
ValKeyPass: env("VALKEY_PASSWORD", ""),
ValKeyDB: envInt("VALKEY_DB", 0),
JWTSecret: []byte(env("JWT_SECRET", "")),
JWTTTL: time.Duration(envInt("JWT_TTL_HOURS", 720)) * time.Hour,
SessionRenewLast: time.Duration(envInt("SESSION_RENEW_LAST_HOURS", 168)) * time.Hour,
S3: S3Config{
Endpoint: env("S3_ENDPOINT", ""),
Region: env("S3_REGION", "us-east-1"),
Bucket: env("S3_BUCKET", "article-media"),
AccessKey: env("S3_ACCESS_KEY", ""),
SecretKey: env("S3_SECRET_KEY", ""),
PublicBase: env("S3_PUBLIC_BASE", ""),
},
RateLimit: RateLimitConfig{
AnonPerMinute: envInt("RATE_ANON_PER_MIN", 120),
UserPerMinute: envInt("RATE_USER_PER_MIN", 600),
},
OTLPEnabledpoint: env("OTLP_ENDPOINT", ""),
TraceSampleRatio: envFloat("TRACE_SAMPLE_RATIO", 1.0),
CORSOrigins: splitCSV(env("CORS_ORIGINS", "http://127.0.0.1:3100,http://localhost:3100")),
}
if c.PGDSN == "" {
return nil, fmt.Errorf("PG_DSN 未设置")
}
// 生产必须显式提供密钥:随机密钥会导致重启后所有登录态失效
if len(c.JWTSecret) < 32 {
if c.Env == "prod" {
return nil, fmt.Errorf("生产环境 JWT_SECRET 必须 >= 32 字节")
}
return nil, fmt.Errorf("JWT_SECRET 未设置或过短(当前 %d 字节,需要 >= 32)", len(c.JWTSecret))
}
return c, nil
}
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
func splitCSV(s string) []string {
if s == "" {
return nil
}
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
return out
}
func envFloat(k string, def float64) float64 {
if v := os.Getenv(k); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
}
return def
}
func envInt(k string, def int) int {
if v := os.Getenv(k); v != "" {
if n, err := strconv.Atoi(v); err == nil {
return n
}
}
return def
}