新增注释

This commit is contained in:
2026-05-09 17:50:40 +08:00
parent d5c053e59d
commit 8504838ccb
19 changed files with 404 additions and 217 deletions
+21 -10
View File
@@ -2,26 +2,37 @@ package config
import (
"fmt"
"github.com/spf13/viper"
)
// Config 描述 config.yaml 中使用到的应用配置。
//
// Database 保存 MySQL 连接参数,Server 保存 HTTP 服务参数。结构体字段名需要与配置文件
// 中的层级保持一致,Viper 会在 InitConfig 中把 YAML 内容反序列化到该结构体。
type Config struct {
// Database 是 MySQL 连接配置。
Database struct {
User string
Password string
Host string
Port int
Dbname string
Charset string
Collation string
User string // 数据库用户名。
Password string // 数据库密码。
Host string // 数据库主机地址。
Port int // 数据库端口。
Dbname string // 数据库名称。
Charset string // 连接字符集,例如 utf8mb4。
Collation string // 排序规则;为空时 GetDSN 会使用 utf8mb4_unicode_ci。
}
// Server 是 HTTP 服务配置。
Server struct {
Port int
Port int // 服务监听端口。
}
}
// AppConfig 保存进程级全局配置。调用 InitConfig 后才可安全读取。
var AppConfig *Config
// InitConfig 从当前目录或 ./config 目录读取 config.yaml,并解析到 AppConfig。
//
// 这里使用 panic 暴露配置错误,因为配置缺失或格式错误会导致服务无法正确启动。
func InitConfig() {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
@@ -37,7 +48,7 @@ func InitConfig() {
}
}
// GetDSN 生成 MySQL 连接字符串
// GetDSN 根据 AppConfig 生成 GORM/MySQL 使用的 DSN 连接字符串。
func GetDSN() string {
db := AppConfig.Database
collation := db.Collation
@@ -48,7 +59,7 @@ func GetDSN() string {
db.User, db.Password, db.Host, db.Port, db.Dbname, db.Charset, collation)
}
// GetServerPort 获取服务器端口字符串
// GetServerPort 返回 Gin Run 所需的端口格式,例如 ":8080"。
func GetServerPort() string {
return fmt.Sprintf(":%d", AppConfig.Server.Port)
}