package config
|
|
import (
|
"fmt"
|
"log"
|
"os"
|
|
"gopkg.in/yaml.v3"
|
)
|
|
// ServerConfig 服务相关配置
|
type ServerConfig struct {
|
Port int `yaml:"port"`
|
}
|
|
// MySQLConfig 数据库相关配置
|
type MySQLConfig struct {
|
Host string `yaml:"host"`
|
Port int `yaml:"port"`
|
User string `yaml:"user"`
|
Password string `yaml:"password"`
|
Database string `yaml:"database"`
|
Charset string `yaml:"charset"`
|
}
|
|
// Config 配置文件结构
|
type Config struct {
|
Server ServerConfig `yaml:"server"`
|
MySQL MySQLConfig `yaml:"mysql"`
|
}
|
|
// App 全局配置
|
var App Config
|
|
// Load 读取并解析配置文件
|
func Load(path string) {
|
data, err := os.ReadFile(path)
|
if err != nil {
|
log.Fatalf("读取配置文件失败: %v", err)
|
}
|
if err := yaml.Unmarshal(data, &App); err != nil {
|
log.Fatalf("解析配置文件失败: %v", err)
|
}
|
// 缺省值
|
if App.Server.Port == 0 {
|
App.Server.Port = 8080
|
}
|
if App.MySQL.Port == 0 {
|
App.MySQL.Port = 3306
|
}
|
if App.MySQL.Charset == "" {
|
App.MySQL.Charset = "utf8mb4"
|
}
|
}
|
|
// DSN 拼接 MySQL 连接串
|
func (m MySQLConfig) DSN() string {
|
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
|
m.User, m.Password, m.Host, m.Port, m.Database, m.Charset)
|
}
|