65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
// Package config xxx
|
|
package config
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/spf13/viper"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// Configuration 配置
|
|
type Configuration struct {
|
|
Viper *viper.Viper `yaml:"-"`
|
|
Base *BaseConf `yaml:"base"`
|
|
Logger *LogConf `yaml:"logger"`
|
|
}
|
|
|
|
// New 新增配置
|
|
func New() *Configuration {
|
|
c := &Configuration{}
|
|
|
|
c.Base = NewBaseConf()
|
|
c.Logger = NewLogConf()
|
|
return c
|
|
}
|
|
|
|
// IsLocalEnv 是否本地开发模式
|
|
func (c *Configuration) IsLocalEnv() bool {
|
|
return c.Base.RunEnv == LocalEnv
|
|
}
|
|
|
|
// IsProdEnv 是否生产环境
|
|
func (c *Configuration) IsProdEnv() bool {
|
|
return c.Base.RunEnv == ProdEnv
|
|
}
|
|
|
|
// ReadFrom read from file, should copy if embedded
|
|
func (c *Configuration) ReadFrom(content []byte) error {
|
|
if err := yaml.Unmarshal(content, c); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// ReadFromViper : read from viper, should copy if embedded
|
|
func (c *Configuration) ReadFromViper(v *viper.Viper) error {
|
|
// viper会把所有key处理为小写且不支持inline, 直接使用 yaml 库
|
|
content, err := os.ReadFile(v.ConfigFileUsed())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.Viper = v
|
|
|
|
return c.ReadFrom(content)
|
|
}
|
|
|
|
// OutConf : print conf, should copy if embedded
|
|
func (c *Configuration) OutConf(w io.Writer) error {
|
|
encoder := yaml.NewEncoder(w)
|
|
encoder.SetIndent(2)
|
|
return encoder.Encode(c)
|
|
}
|