| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- package config
- import (
- "fmt"
- "github.com/spf13/viper"
- "os"
- )
- // 初始化配置文件 -- 当存在则不做处理
- func ConfInit() error {
- //fmt.Println("begin create config...")
- createAppConfig()
- //fmt.Println(fmt.Sprintf("create app config:%s", "success"))
- createEnvConfig()
- //fmt.Println(fmt.Sprintf("create env config:%s", "success"))
- return nil
- }
- func createAppConfig() {
- vp := viper.New()
- vp.SetConfigFile(ConfigAppFile)
- setDefaultAppConfig(vp) // 设置默认配置
- saveConfigFile(vp) // 文件读取 如果读取不到则生成(dev环境)
- if err := vp.Unmarshal(&appConf); err != nil {
- panic(err)
- }
- }
- // 保存配置文件
- func saveConfigFile(vp *viper.Viper) {
- err := vp.ReadInConfig()
- if err != nil {
- if _, err = os.Stat(ConfigDir); os.IsNotExist(err) {
- err = os.Mkdir(ConfigDir, 0755)
- if err != nil {
- panic(err)
- }
- }
- if err := vp.WriteConfig(); err != nil {
- panic(fmt.Errorf("Fatal error config file: %s \n", err))
- }
- }
- }
- func createEnvConfig() {
- configFile := GetConfigFileByMod(ModEnvDev)
- vp := viper.New()
- vp.SetConfigFile(configFile)
- vp.SetConfigType("json")
- setDefaultEnvConfig(vp)
- saveConfigFile(vp) // 文件读取 如果读取不到则生成(dev环境)
- if err := vp.Unmarshal(&envConfig); err != nil {
- panic(err)
- }
- }
- // 环境配置初始化
- func setDefaultAppConfig(vp *viper.Viper) {
- vp.SetConfigType("json")
- vp.SetDefault("api_addr", BizHostPort)
- vp.SetDefault("job_addr", JobHostPort)
- vp.SetDefault("mod", "dev")
- vp.SetDefault("router_prefix", "")
- }
- func setDefaultEnvConfig(vp *viper.Viper) {
- vp.SetDefault("jwt", &JWT{
- SigningKey: fmt.Sprintf("%s!@#¥Secret", SignSystemName),
- ExpiresTime: 24,
- Issuer: "app",
- })
- vp.SetDefault("exchange", &Exchange{
- RootUrl: "https://www.jcwork.club",
- Appid: "2hhaivh1CjEKhb7Q",
- Secret: "m6iITfTEsMVHkLRG2JP9Qn1HmxvFKfBTPyAl6evNnmJXRqCxVj4GLqmY2KFuG4Mh",
- })
- vp.SetDefault("mysql", &Mysql{
- GeneralDB: GeneralDB{
- Prefix: "",
- Port: "3306",
- Config: `charset=utf8mb4&parseTime=True&loc=Local`,
- Dbname: BizDbName,
- Username: "root",
- Password: "123456",
- Path: "127.0.0.1",
- Engine: "",
- LogMode: "error",
- MaxIdleConns: 10,
- MaxOpenConns: 10,
- Singular: false,
- LogZap: false,
- }})
- vp.SetDefault("zap", &Zap{
- TagName: "app",
- Level: "debug",
- Prefix: "APP_",
- Format: "_json",
- Director: "logs",
- EncodeLevel: "LowercaseLevelEncoder",
- StacktraceKey: "error",
- MaxAge: 10,
- RotationSize: 100,
- RotationCount: 10,
- ShowLine: true,
- LogInConsole: true,
- LogOutputFile: true,
- })
- vp.SetDefault("redis", &Redis{
- Addr: "127.0.0.1:6379",
- Password: "",
- Db: 0,
- EnabledTls: false,
- EnabledCluster: false,
- Cluster: []string{"127.0.0.1:6379"},
- })
- }
|