13
This commit is contained in:
55
config/config.go
Normal file
55
config/config.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DBHost string
|
||||
DBPort string
|
||||
DBUser string
|
||||
DBPassword string
|
||||
DBName string
|
||||
JWTSecret string
|
||||
ServerPort string
|
||||
}
|
||||
|
||||
func LoadConfig() *Config {
|
||||
// 加载 .env 文件
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Println("警告: 未找到 .env 文件,使用环境变量")
|
||||
}
|
||||
|
||||
config := &Config{
|
||||
DBHost: getEnv("DB_HOST", "localhost"),
|
||||
DBPort: getEnv("DB_PORT", "3306"),
|
||||
DBUser: getEnv("DB_USER", "root"),
|
||||
DBPassword: getEnv("DB_PASSWORD", ""),
|
||||
DBName: getEnv("DB_NAME", "appointment_db"),
|
||||
JWTSecret: getEnv("JWT_SECRET", "your-secret-key"),
|
||||
ServerPort: getEnv("SERVER_PORT", "3000"),
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func getEnvAsInt(key string, defaultValue int) int {
|
||||
if valueStr := os.Getenv(key); valueStr != "" {
|
||||
if value, err := strconv.Atoi(valueStr); err == nil {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
Reference in New Issue
Block a user