go17/book/config/load.go

49 lines
935 B
Go
Raw Normal View History

2024-11-16 16:00:55 +08:00
package config
2024-11-16 17:22:21 +08:00
import (
"os"
"gopkg.in/yaml.v3"
)
// 程序的配置需要有默认值, 给一个最小的可以运行的配置: 本地开发配置就是默认配置
// "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,
},
}
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)
}