2024-11-16 16:00:55 +08:00
|
|
|
package config
|
|
|
|
|
2024-11-16 17:22:21 +08:00
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
|
2024-11-23 15:17:11 +08:00
|
|
|
"github.com/rs/zerolog"
|
2024-11-16 17:22:21 +08:00
|
|
|
"gopkg.in/yaml.v3"
|
2024-11-23 15:17:11 +08:00
|
|
|
"gorm.io/gorm"
|
2024-11-16 17:22:21 +08:00
|
|
|
)
|
|
|
|
|
2024-11-23 15:17:11 +08:00
|
|
|
// 补充一些全局变量的快捷方式,方便全局使用
|
|
|
|
func L() *gorm.DB {
|
|
|
|
return Get().MySQL.DB()
|
|
|
|
}
|
|
|
|
|
2024-11-16 17:22:21 +08:00
|
|
|
// 程序的配置需要有默认值, 给一个最小的可以运行的配置: 本地开发配置就是默认配置
|
|
|
|
// "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
|
|
|
|
var conf = &Config{
|
|
|
|
App: &App{
|
|
|
|
Host: "127.0.0.1",
|
|
|
|
Port: 8080,
|
|
|
|
},
|
|
|
|
MySQL: &MySQL{
|
|
|
|
Host: "127.0.0.1",
|
|
|
|
Port: 3306,
|
|
|
|
Database: "test",
|
|
|
|
Username: "root",
|
|
|
|
Password: "123456",
|
|
|
|
Debug: true,
|
|
|
|
},
|
2024-11-23 15:17:11 +08:00
|
|
|
Log: &Log{
|
|
|
|
CallerDeep: 3,
|
|
|
|
Level: zerolog.DebugLevel,
|
|
|
|
Console: Console{
|
|
|
|
Enable: true,
|
|
|
|
NoColor: true,
|
|
|
|
},
|
|
|
|
File: File{
|
|
|
|
Enable: true,
|
|
|
|
MaxSize: 100,
|
|
|
|
MaxBackups: 6,
|
|
|
|
},
|
|
|
|
},
|
2024-11-16 17:22:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func Get() *Config {
|
|
|
|
if conf == nil {
|
|
|
|
panic("配置未初始化")
|
|
|
|
}
|
|
|
|
|
|
|
|
return conf
|
|
|
|
}
|
|
|
|
|
2024-11-16 16:00:55 +08:00
|
|
|
// 配置的加载
|
|
|
|
|
|
|
|
// 程序的其他的部分如何读写程序配置
|
2024-11-16 17:22:21 +08:00
|
|
|
// Yaml File ---> Config
|
|
|
|
func LoadConfigFromYaml(configFilePath string) error {
|
|
|
|
content, err := os.ReadFile(configFilePath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// 默认值 defaultConfig
|
|
|
|
// 结合配置文件 传达进来的 参数
|
|
|
|
// defualt <-- user defile
|
|
|
|
return yaml.Unmarshal(content, conf)
|
|
|
|
}
|