搭建用户体系
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user