Files
stock/backend/internal/config/config.go
T
2026-07-04 14:46:38 +08:00

65 lines
1.3 KiB
Go

package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/joho/godotenv"
)
type Config struct {
DatabaseURL string
JWTSecret string
JWTExpirationHours int
Port string
AllowedOrigins []string
}
func Load() (*Config, error) {
_ = godotenv.Load()
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
return nil, fmt.Errorf("DATABASE_URL must be set")
}
jwtSecret := os.Getenv("JWT_SECRET")
if jwtSecret == "" {
jwtSecret = "change-me-in-production"
fmt.Fprintln(os.Stderr, "WARNING: JWT_SECRET not set, using default secret")
}
expHours, _ := strconv.Atoi(os.Getenv("JWT_EXPIRATION_HOURS"))
if expHours == 0 {
expHours = 168 // 7 days
}
port := os.Getenv("PORT")
if port == "" {
port = "3019"
}
allowedOrigins := []string{"*"}
if v := os.Getenv("ALLOWED_ORIGINS"); v != "" {
allowedOrigins = strings.Split(v, ",")
for i := range allowedOrigins {
allowedOrigins[i] = strings.TrimSpace(allowedOrigins[i])
}
}
return &Config{
DatabaseURL: databaseURL,
JWTSecret: jwtSecret,
JWTExpirationHours: expHours,
Port: port,
AllowedOrigins: allowedOrigins,
}, nil
}
func (c *Config) JWTExpiration() time.Duration {
return time.Duration(c.JWTExpirationHours) * time.Hour
}