golib/gconfig/config.go

61 lines
1.2 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// config.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package gconfig
import (
"bytes"
"io/ioutil"
"text/template"
"hexq.cn/tiglog/golib/gfile"
"gopkg.in/yaml.v2"
"hexq.cn/tiglog/golib/helper"
)
type BaseConfig struct {
BaseDir string
Http HttpConfig `json:"http" yaml:"http"`
Auth AuthConfig `json:"auth" yaml:"auth"`
Param ParamConfig `json:"param" yaml:"param"`
Db DbConfig `json:"db" yaml:"db"`
Mongo MongoConfig `json:"mongo" yaml:"mongo"`
Redis RedisConfig `json:"redis" yaml:"redis"`
}
func (c *BaseConfig) LoadParams() {
if c.BaseDir == "" {
c.BaseDir = "./etc"
}
c.Param.Load(c.BaseDir + "/params.yaml")
}
func (c *BaseConfig) ParseAppConfig() {
buf := c.GetData("/app.yaml", true)
err := yaml.Unmarshal(buf.Bytes(), c)
helper.CheckErr(err)
}
func (c *BaseConfig) GetData(fname string, must bool) *bytes.Buffer {
fp := c.BaseDir + fname
if !gfile.Exists(fp) {
if must {
panic("配置文件" + fp + "不存在")
} else {
return nil
}
}
dat, err := ioutil.ReadFile(fp)
helper.CheckErr(err)
tpl, err := template.New("config").Parse(string(dat))
helper.CheckErr(err)
buf := new(bytes.Buffer)
tpl.Execute(buf, c.Param.Params)
return buf
}