DriveLinked/config/config.go

105 lines
1.8 KiB
Go

package config
import (
"bytes"
"drive-linked/pkg/utils"
_ "embed"
"github.com/kataras/golog"
"gopkg.in/yaml.v2"
"html/template"
"io/ioutil"
"os"
)
type Config struct {
Version string
App struct {
Host string
port uint16
}
Security struct {
AllowCORS []string `yaml:"allow-CORS"`
Jwt struct {
Expire uint32
RefreshExpire uint32 `yaml:"refresh-expire"`
Secret string
}
}
Database struct {
Driver string
Dsn string
}
}
var Cfg Config
//go:embed config.full.yml
var configFull string
// 加载配置文件
func SetupConfig() {
// 加载默认配置
Cfg = DefCfg
// 读取配置文件,若不存在则创建
if isExist := utils.FileExist("config.yml"); !isExist {
newCfgFile()
}
// 读取文件
cfgFile, err := os.OpenFile("config.yml", os.O_RDONLY, 0755)
if err != nil {
golog.Fatal(err)
}
cfgContent, err := ioutil.ReadAll(cfgFile)
if err != nil {
golog.Fatal(err)
}
// 解析文件
err = yaml.Unmarshal(cfgContent, &Cfg)
if err != nil {
golog.Fatal(err)
}
golog.Debug("Loaded config: ", Cfg)
}
// 解析配置文件模板
func parseConfigTmpl() []byte {
// 加载模板
cfgTmpl, err := template.New("config.full.yml").Parse(configFull)
if err != nil {
golog.Fatal(err)
}
// 解析
var tmplBytes bytes.Buffer
err = cfgTmpl.Execute(&tmplBytes, Cfg)
if err != nil {
golog.Fatal(err)
}
return tmplBytes.Bytes()
}
// 创建配置文件
func newCfgFile() {
// 生成Key
Cfg.Security.Jwt.Secret = utils.NewKey()
// 解析配置文件模板
tmplBytes := parseConfigTmpl()
// 生成新配置文件config.yml
cfgFile, err := os.OpenFile("config.yml", os.O_CREATE, 0755)
if err != nil {
golog.Fatal(err)
}
defer cfgFile.Close()
_, err = cfgFile.Write(tmplBytes)
if err != nil {
golog.Fatal(err)
}
}