905086
2026-11-09 cbb26873e88a7a13e868448c1cc578ce70b8c6ae
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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)
}