package config import ( "os" "github.com/rs/zerolog" "gopkg.in/yaml.v3" "gorm.io/gorm" ) // 补充一些全局变量的快捷方式,方便全局使用 func L() *gorm.DB { return Get().MySQL.DB() } // 程序的配置需要有默认值, 给一个最小的可以运行的配置: 本地开发配置就是默认配置 // "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, }, Log: &Log{ CallerDeep: 3, Level: zerolog.DebugLevel, Console: Console{ Enable: true, NoColor: true, }, File: File{ Enable: true, MaxSize: 100, MaxBackups: 6, }, }, } func Get() *Config { if conf == nil { panic("配置未初始化") } return conf } // 配置的加载 // 程序的其他的部分如何读写程序配置 // 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) }