suyiiyii 56839f5ded
build(conf): 更新配置文件处理依赖
- 在 app/facade/conf 和 app/user/conf 模块中添加 validator 和 yaml 库的导入
- 调整导入库的顺序,提高代码可读性
2025-01-20 23:46:29 +08:00

113 lines
2.1 KiB
Go

package conf
import (
_ "embed"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/kr/pretty"
"gopkg.in/validator.v2"
"gopkg.in/yaml.v2"
"os"
"sync"
)
var (
conf *Config
once sync.Once
)
type Config struct {
Env string
Hertz Hertz `yaml:"hertz"`
MySQL MySQL `yaml:"mysql"`
Redis Redis `yaml:"redis"`
}
type MySQL struct {
DSN string `yaml:"dsn"`
}
type Redis struct {
Address string `yaml:"address"`
Password string `yaml:"password"`
Username string `yaml:"username"`
DB int `yaml:"db"`
}
type Hertz struct {
Service string `yaml:"service"`
Address string `yaml:"address"`
EnablePprof bool `yaml:"enable_pprof"`
EnableGzip bool `yaml:"enable_gzip"`
EnableAccessLog bool `yaml:"enable_access_log"`
LogLevel string `yaml:"log_level"`
LogFileName string `yaml:"log_file_name"`
LogMaxSize int `yaml:"log_max_size"`
LogMaxBackups int `yaml:"log_max_backups"`
LogMaxAge int `yaml:"log_max_age"`
}
// GetConf gets configuration instance
func GetConf() *Config {
once.Do(initConf)
return conf
}
//go:embed dev/conf.yaml
var configFile []byte
func initConf() {
//prefix := "conf"
//confFileRelPath := filepath.Join(prefix, filepath.Join(GetEnv(), "conf.yaml"))
//content, err := ioutil.ReadFile(confFileRelPath)
//if err != nil {
// panic(err)
//}
conf = new(Config)
err := yaml.Unmarshal(configFile, conf)
if err != nil {
hlog.Error("parse yaml error - %v", err)
panic(err)
}
if err := validator.Validate(conf); err != nil {
hlog.Error("validate config error - %v", err)
panic(err)
}
conf.Env = GetEnv()
pretty.Printf("%+v\n", conf)
}
func GetEnv() string {
e := os.Getenv("GO_ENV")
if len(e) == 0 {
return "test"
}
return e
}
func LogLevel() hlog.Level {
level := GetConf().Hertz.LogLevel
switch level {
case "trace":
return hlog.LevelTrace
case "debug":
return hlog.LevelDebug
case "info":
return hlog.LevelInfo
case "notice":
return hlog.LevelNotice
case "warn":
return hlog.LevelWarn
case "error":
return hlog.LevelError
case "fatal":
return hlog.LevelFatal
default:
return hlog.LevelInfo
}
}