修改配置文件单例模式

This commit is contained in:
何昌清
2026-03-27 14:20:20 +08:00
parent 5dd7bb9709
commit d289800092
7 changed files with 58 additions and 64 deletions

View File

@@ -2,92 +2,90 @@ package config
import ( import (
"os" "os"
"sync"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
// Config 结构体定义了应用程序的所有配置项 // Config 结构体定义了应用程序的所有配置项
type Config struct { type Config struct {
// 数据库配置
DB struct { DB struct {
Host string `yaml:"host"` // 数据库主机地址 Host string `yaml:"host"`
Port string `yaml:"port"` // 数据库端口 Port string `yaml:"port"`
User string `yaml:"user"` // 数据库用户名 User string `yaml:"user"`
Password string `yaml:"password"` // 数据库密码 Password string `yaml:"password"`
Name string `yaml:"name"` // 数据库名称 Name string `yaml:"name"`
} `yaml:"db"` } `yaml:"db"`
Redis struct { Redis struct {
Host string `yaml:"host"` // Redis主机地址 Host string `yaml:"host"`
Port string `yaml:"port"` // Redis端口 Port string `yaml:"port"`
Password string `yaml:"password"` // Redis密码 Password string `yaml:"password"`
DB string `yaml:"db"` // Redis数据库索引 DB string `yaml:"db"`
} `yaml:"redis"` } `yaml:"redis"`
// 服务器配置
Server struct { Server struct {
Port string `yaml:"port"` // 服务器监听端口 Port string `yaml:"port"`
Mode string `yaml:"mode"` // 运行模式 Mode string `yaml:"mode"`
} `yaml:"server"` } `yaml:"server"`
Jwt struct { Jwt struct {
Secret string `yaml:"secret"` // JWT 密钥 Secret string `yaml:"secret"`
Expire string `yaml:"expire"` // JWT 过期时间(单位:小时) Expire string `yaml:"expire"`
} `yaml:"jwt"` } `yaml:"jwt"`
// mmdb 配置
Mmdb struct { Mmdb struct {
Path string `yaml:"path"` // mmdb 文件路径 Path string `yaml:"path"`
} `yaml:"mmdb"` } `yaml:"mmdb"`
// 日志配置
Log struct { Log struct {
Path string `yaml:"path"` // 日志目录路径 Path string `yaml:"path"`
} `yaml:"log"` } `yaml:"log"`
} }
// LoadConfig 加载并返回应用程序配置 var (
configInstance *Config
configOnce sync.Once
)
// LoadConfig 加载并返回应用程序配置(单例模式,只加载一次)
func LoadConfig() *Config { func LoadConfig() *Config {
// 首先尝试从配置文件加载 configOnce.Do(func() {
if cfg := loadConfigFromFile(); cfg != nil { if cfg := loadConfigFromFile(); cfg != nil {
return cfg configInstance = cfg
return
} }
// 如果没有配置文件,则使用环境变量或默认值
cfg := &Config{} cfg := &Config{}
// 数据库配置
cfg.DB.Host = getEnv("DB_HOST", "localhost") cfg.DB.Host = getEnv("DB_HOST", "localhost")
cfg.DB.Port = getEnv("DB_PORT", "3306") cfg.DB.Port = getEnv("DB_PORT", "3306")
cfg.DB.User = getEnv("DB_USER", "root") cfg.DB.User = getEnv("DB_USER", "root")
cfg.DB.Password = getEnv("DB_PASSWORD", "123456") cfg.DB.Password = getEnv("DB_PASSWORD", "123456")
cfg.DB.Name = getEnv("DB_NAME", "quincy") cfg.DB.Name = getEnv("DB_NAME", "quincy")
// Redis 配置
cfg.Redis.Host = getEnv("REDIS_HOST", "localhost") cfg.Redis.Host = getEnv("REDIS_HOST", "localhost")
cfg.Redis.Port = getEnv("REDIS_PORT", "6379") cfg.Redis.Port = getEnv("REDIS_PORT", "6379")
cfg.Redis.Password = getEnv("REDIS_PASSWORD", "") cfg.Redis.Password = getEnv("REDIS_PASSWORD", "")
cfg.Redis.DB = getEnv("REDIS_DB", "0") cfg.Redis.DB = getEnv("REDIS_DB", "0")
// 服务器配置
cfg.Server.Port = getEnv("SERVER_PORT", "8080") cfg.Server.Port = getEnv("SERVER_PORT", "8080")
cfg.Server.Mode = getEnv("SERVER_MODE", "debug") cfg.Server.Mode = getEnv("SERVER_MODE", "debug")
// Jwt 配置
cfg.Jwt.Secret = getEnv("JWT_SECRET", "your-secret-key") cfg.Jwt.Secret = getEnv("JWT_SECRET", "your-secret-key")
cfg.Jwt.Expire = getEnv("JWT_EXPIRE", "24") cfg.Jwt.Expire = getEnv("JWT_EXPIRE", "24")
// mmdb 配置
cfg.Mmdb.Path = getEnv("MMDB_PATH", "./GeoLite2-City.mmdb") cfg.Mmdb.Path = getEnv("MMDB_PATH", "./GeoLite2-City.mmdb")
cfg.Log.Path = getEnv("LOG_DIR", "./") cfg.Log.Path = getEnv("LOG_DIR", "./")
return cfg configInstance = cfg
})
return configInstance
} }
// loadConfigFromFile 从配置文件加载配置
func loadConfigFromFile() *Config { func loadConfigFromFile() *Config {
// 尝试加载 yaml 配置文件
if data, err := os.ReadFile("/home/app/quincy/default.yaml"); err == nil { if data, err := os.ReadFile("/home/app/quincy/default.yaml"); err == nil {
cfg := &Config{} cfg := &Config{}
if err := yaml.Unmarshal(data, cfg); err == nil { if err := yaml.Unmarshal(data, cfg); err == nil {
@@ -97,7 +95,6 @@ func loadConfigFromFile() *Config {
return nil return nil
} }
// getEnv 获取环境变量,如果不存在则返回默认值
func getEnv(key, defaultValue string) string { func getEnv(key, defaultValue string) string {
value := os.Getenv(key) value := os.Getenv(key)
if value == "" { if value == "" {

View File

@@ -2226,7 +2226,7 @@ const docTemplate = `{
"securityDefinitions": { "securityDefinitions": {
"ApiKeyAuth": { "ApiKeyAuth": {
"type": "apiKey", "type": "apiKey",
"name": "X-Access-Token", "name": "Authorization",
"in": "header" "in": "header"
} }
} }

View File

@@ -2220,7 +2220,7 @@
"securityDefinitions": { "securityDefinitions": {
"ApiKeyAuth": { "ApiKeyAuth": {
"type": "apiKey", "type": "apiKey",
"name": "X-Access-Token", "name": "Authorization",
"in": "header" "in": "header"
} }
} }

View File

@@ -1395,6 +1395,6 @@ paths:
securityDefinitions: securityDefinitions:
ApiKeyAuth: ApiKeyAuth:
in: header in: header
name: X-Access-Token name: Authorization
type: apiKey type: apiKey
swagger: "2.0" swagger: "2.0"

View File

@@ -23,7 +23,7 @@ import (
// @BasePath /quin // @BasePath /quin
// @securityDefinitions.apikey ApiKeyAuth // @securityDefinitions.apikey ApiKeyAuth
// @in header // @in header
// @name X-Access-Token // @name Authorization
func main() { func main() {
//===================================加载配置==================================== //===================================加载配置====================================
cfg := config.LoadConfig() cfg := config.LoadConfig()

View File

@@ -26,9 +26,9 @@ func RequestResponseLogger() gin.HandlerFunc {
// 获取请求头信息 // 获取请求头信息
var headers string var headers string
Token := ctx.GetHeader("X-Access-Token") _ = ctx.GetHeader("Authorization")
headers = fmt.Sprintf("X-Access-Token: %s; ", Token) //headers = fmt.Sprintf("Authorization: %s; ", Token)
// 记录开始时间 // 记录开始时间
startTime := time.Now() startTime := time.Now()

View File

@@ -20,7 +20,6 @@ type Claims struct {
// GenerateToken 生成 JWT token // GenerateToken 生成 JWT token
func GenerateToken(userID int, username, sessionCode string, roleCode int) (string, error) { func GenerateToken(userID int, username, sessionCode string, roleCode int) (string, error) {
// 从配置文件或其他地方获取密钥,这里先使用硬编码的密钥
cfg := config.LoadConfig() cfg := config.LoadConfig()
secretKey := []byte(cfg.Jwt.Secret) secretKey := []byte(cfg.Jwt.Secret)
@@ -32,7 +31,6 @@ func GenerateToken(userID int, username, sessionCode string, roleCode int) (stri
expirationTime := time.Now().Add(time.Duration(expireHours) * time.Hour) expirationTime := time.Now().Add(time.Duration(expireHours) * time.Hour)
// 创建 JWT 声明
claims := &Claims{ claims := &Claims{
UserID: userID, UserID: userID,
Username: username, Username: username,
@@ -45,18 +43,18 @@ func GenerateToken(userID int, username, sessionCode string, roleCode int) (stri
}, },
} }
// 创建 token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// 签名并获取完整的 token 字符串
return token.SignedString(secretKey) return token.SignedString(secretKey)
} }
// ParseToken 解析 JWT token // ParseToken 解析 JWT token
func ParseToken(tokenString string) (*Claims, error) {
secretKey := []byte("hcq")
// 解析 token func ParseToken(tokenString string) (*Claims, error) {
cfg := config.LoadConfig()
secretKey := []byte(cfg.Jwt.Secret)
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) { token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("unexpected signing method") return nil, errors.New("unexpected signing method")
@@ -68,7 +66,6 @@ func ParseToken(tokenString string) (*Claims, error) {
return nil, err return nil, err
} }
// 验证并返回 claims
if claims, ok := token.Claims.(*Claims); ok && token.Valid { if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil return claims, nil
} }