Files
go/pkg/config/config.go
T

55 lines
1.2 KiB
Go

package config
import (
"fmt"
"github.com/spf13/viper"
)
type Config struct {
Database struct {
User string
Password string
Host string
Port int
Dbname string
Charset string
Collation string
}
Server struct {
Port int
}
}
var AppConfig *Config
func InitConfig() {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".") // 在当前目录查找 config.yaml
viper.AddConfigPath("./config") // 兼容多一层目录的情况
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Errorf("无法读取配置文件: %w", err))
}
if err := viper.Unmarshal(&AppConfig); err != nil {
panic(fmt.Errorf("无法解析配置结构体: %w", err))
}
}
// GetDSN 生成 MySQL 连接字符串
func GetDSN() string {
db := AppConfig.Database
collation := db.Collation
if collation == "" {
collation = "utf8mb4_unicode_ci"
}
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&collation=%s&parseTime=True&loc=Local",
db.User, db.Password, db.Host, db.Port, db.Dbname, db.Charset, collation)
}
// GetServerPort 获取服务器端口字符串
func GetServerPort() string {
return fmt.Sprintf(":%d", AppConfig.Server.Port)
}