86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
|
package conf
|
|||
|
|
|||
|
import (
|
|||
|
"encoding/json"
|
|||
|
"github.com/BurntSushi/toml"
|
|||
|
"github.com/mcuadros/go-defaults"
|
|||
|
"mc-client-updater-server/pkg/log"
|
|||
|
"mc-client-updater-server/pkg/util"
|
|||
|
"os"
|
|||
|
)
|
|||
|
|
|||
|
type Config struct {
|
|||
|
Common Common `toml:"common"`
|
|||
|
Database Database `toml:"database"`
|
|||
|
Security Security `toml:"security"`
|
|||
|
}
|
|||
|
|
|||
|
type Common struct {
|
|||
|
Host string `toml:"host" default:"0.0.0.0"`
|
|||
|
Port uint16 `toml:"port" default:"8080"`
|
|||
|
}
|
|||
|
|
|||
|
type Database struct {
|
|||
|
Host string `toml:"host" default:"localhost"`
|
|||
|
Port uint16 `toml:"port" default:"5432"`
|
|||
|
User string `toml:"user" default:"user"`
|
|||
|
Password string `toml:"password" default:"password"`
|
|||
|
DB string `toml:"db" default:"mc_client_updater"`
|
|||
|
}
|
|||
|
|
|||
|
type Security struct {
|
|||
|
PasswordEncoder string `toml:"password_encoder" default:"argon2id"`
|
|||
|
JWTSecret string `toml:"jwt_secret"`
|
|||
|
}
|
|||
|
|
|||
|
var (
|
|||
|
Conf *Config
|
|||
|
)
|
|||
|
|
|||
|
// 释放默认配置文件
|
|||
|
func releaseConfig(file string, config *Config) {
|
|||
|
f, err := util.CreateNestedFile(file)
|
|||
|
if err != nil {
|
|||
|
log.Logger.Fatalf("创建默认配置文件失败: %s", err.Error())
|
|||
|
}
|
|||
|
|
|||
|
if config.Security.JWTSecret == "" {
|
|||
|
config.Security.JWTSecret = util.RandStr(32)
|
|||
|
}
|
|||
|
|
|||
|
encoder := toml.NewEncoder(f)
|
|||
|
err = encoder.Encode(config)
|
|||
|
if err != nil {
|
|||
|
log.Logger.Fatalf("创建默认配置文件失败: %s", err.Error())
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
func InitConfig(file string) {
|
|||
|
Conf = &Config{}
|
|||
|
defaults.SetDefaults(Conf)
|
|||
|
|
|||
|
if util.NotExists(file) {
|
|||
|
// 默认配置文件不存在则创建
|
|||
|
if file == "config.toml" {
|
|||
|
releaseConfig(file, Conf)
|
|||
|
log.Logger.Infof("已创建默认配置文件: %s,请修改配置文件内容后重新启动", file)
|
|||
|
os.Exit(0)
|
|||
|
} else {
|
|||
|
log.Logger.Fatalf("配置文件不存在: %s", file)
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
// 解析配置文件
|
|||
|
_, err := toml.DecodeFile(file, &Conf)
|
|||
|
if err != nil {
|
|||
|
log.Logger.Fatalf("配置文件解析出错: %s", err.Error())
|
|||
|
}
|
|||
|
|
|||
|
// 配置预检查
|
|||
|
|
|||
|
jsonConfig, err := json.Marshal(Conf)
|
|||
|
if err == nil {
|
|||
|
log.Logger.Debugf("配置文件已加载: %s", string(jsonConfig))
|
|||
|
}
|
|||
|
}
|