100 lines
2.0 KiB
Go
100 lines
2.0 KiB
Go
package conf
|
|
|
|
import (
|
|
"acme-mana/src/common"
|
|
"acme-mana/src/util"
|
|
"gopkg.in/yaml.v3"
|
|
"log"
|
|
"os"
|
|
)
|
|
|
|
func LoadAppConfig() {
|
|
// 读取配置文件位置
|
|
confFile := getConfFile()
|
|
// 判断配资文件是否存在
|
|
if _, err := os.Stat(confFile); os.IsNotExist(err) {
|
|
log.Println("配置文件不存在, 自动创建")
|
|
config := defaultAppConfig()
|
|
log.Println("默认配置文件创建成功")
|
|
log.Println("服务器通信密钥: " + config.Server.Key)
|
|
appConf = config
|
|
writeConf(appConf, confFile)
|
|
} else {
|
|
appConf = readAppConfig(appConf)
|
|
}
|
|
}
|
|
|
|
// RefreshConfig 刷新配置
|
|
func RefreshConfig() {
|
|
readAppConfig(appConf)
|
|
}
|
|
|
|
// WriteConfig 写入配置文件
|
|
func WriteConfig() {
|
|
confFile, err := common.RootCmd.PersistentFlags().GetString("conf")
|
|
if err != nil {
|
|
log.Fatalln("读取配置文件参数失败")
|
|
}
|
|
writeConf(appConf, confFile)
|
|
}
|
|
|
|
func writeConf(c *AppConfig, file string) {
|
|
out, err := yaml.Marshal(c)
|
|
if err != nil {
|
|
log.Fatalln("序列化配置文件失败")
|
|
}
|
|
util.MkFileDir(file)
|
|
err = os.WriteFile(file, out, 0644)
|
|
if err != nil {
|
|
log.Fatalln("写入配置文件失败")
|
|
}
|
|
}
|
|
|
|
// DefaultAppConfig 默认配置
|
|
func defaultAppConfig() *AppConfig {
|
|
serverKey := util.RandomStr(32)
|
|
|
|
return &AppConfig{
|
|
Server: &ServerConf{
|
|
Host: "0.0.0.0",
|
|
Port: 36851,
|
|
Key: serverKey,
|
|
},
|
|
Web: &WebConf{
|
|
Enable: false,
|
|
Host: "0.0.0.0",
|
|
Port: 36852,
|
|
},
|
|
Task: &TaskConf{
|
|
Delay: 0,
|
|
Interval: 0,
|
|
},
|
|
Certs: nil,
|
|
Providers: nil,
|
|
}
|
|
}
|
|
|
|
// getConfFile 获取配置文件位置
|
|
func getConfFile() string {
|
|
confFile, err := common.RootCmd.PersistentFlags().GetString("conf")
|
|
if err != nil {
|
|
log.Fatalln("读取配置文件参数失败")
|
|
}
|
|
return confFile
|
|
}
|
|
|
|
// readAppConfig 读取配置文件
|
|
func readAppConfig(c *AppConfig) *AppConfig {
|
|
confFile := getConfFile()
|
|
file, err := os.ReadFile(confFile)
|
|
if err != nil {
|
|
log.Fatalln("读取配置文件失败")
|
|
}
|
|
//var conf = &model.AppConfig{}
|
|
err = yaml.Unmarshal(file, c)
|
|
if err != nil {
|
|
log.Fatalln("解析配置文件失败")
|
|
}
|
|
return c
|
|
}
|