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"}, }) vp.SetDefault("file", &File{ OssType: "aws", Path: "http://127.0.0.1:9000", ProxyPath: "/daytask-media", StorePath: "./static", OriginConf: map[string]interface{}{ "bucket": "daytask-media", "region": "us-east-1", "endpoint": "http://127.0.0.1:9000", "secret-id": "minioadmin", "secret-key": "minioadmin", "base-url": "http://127.0.0.1:9000/daytask-media", "path-prefix": "uploads", "s3-force-path-style": true, "disable-ssl": true, }, }) }