package common import ( "encoding/json" "fmt" _ "github.com/jinzhu/gorm/dialects/mssql" _ "github.com/jinzhu/gorm/dialects/mysql" "go.uber.org/zap" "go.uber.org/zap/zapcore" gopkg "gopkg" "gopkg.in/yaml.v2" "io/ioutil" "log" "os" "path" "runtime" "time" ) //serverModel get server information from config.yml type serverModel struct { Mode string `yaml:"mode"` // run mode Host string `yaml:"host"` // server host Port string `yaml:"port"` // server port EnableHttps bool `yaml:"enable_https"` // enable https CertFile string `yaml:"cert_file"` // cert file path KeyFile string `yaml:"key_file"` // key file path JwtPubKeyPath string `yaml:"jwt_public_key_path"` // jwt public key path JwtPriKeyPath string `yaml:"jwt_private_key_path"` // jwt private key path TokenExpireSecond time.Duration `yaml:"token_expire_second"` // token expire second } //databaseModel get database information from config.yml type databaseModel struct { DBType string `yaml:"type"` // db type Host string `yaml:"host"` // db host Port int `yaml:"port"` // db port UserName string `yaml:"username"` // user name Password string `yaml:"password"` // password Database string `yaml:"database"` // database MaxIdle int `yaml:"max_idle"` // db max idle connections MaxOpen int `yaml:"max_open"` // db max open connections } //redisModel get redis information from config.yml type redisModel struct { Host string `yaml:"host"` Port int `yaml:"port"` } //logModel get log information from config.yml type logModel struct { Open bool `yaml:"open"` Mode string `yaml:"mode"` Path string `yaml:"file"` Level string `yaml:"level"` } //imageModel get image information from config.yml type imageModel struct { BasePath string `yaml:"base_path"` OutputDir string `yaml:"output_dir"` PrefixURL string `yaml:"prefix_url"` MaxSize int64 `yaml:"max_size"` } //systemModel get system information from config.yml type systemModel struct { Avatar string `yaml:"avatar"` Sync bool `yaml:"sync"` Valid bool `yaml:"valid"` } type configModel struct { Server *serverModel `yaml:"server"` Database *databaseModel `yaml:"database"` Redis *redisModel `yaml:"redis"` Image *imageModel `yaml:"image"` Log *logModel `yaml:"log"` System *systemModel `yaml:"system"` } // LoadConfigInformation load config information for application func LoadConfigInformation(configPath string) (err error) { var ( filePath string wr string ) if configPath == "" { wr, _ = os.Getwd() wr = path.Join(wr, "conf") } else { wr = configPath } filePath = path.Join(wr, "config.yml") configData, err := ioutil.ReadFile(filePath) if err != nil { fmt.Printf(" config file read failed: %s", err) os.Exit(-1) } err = yaml.Unmarshal(configData, &ConfigInfo) if err != nil { fmt.Printf(" config parse failed: %s", err) os.Exit(-1) } // server information ServerInfo = ConfigInfo.Server // image information ImageInfo = ConfigInfo.Image // log information LoggerInfo = ConfigInfo.Log // system information SystemInfo = ConfigInfo.System // log config load logPath := LoggerInfo.Path //log path logLevel := LoggerInfo.Level // log level isDebug := true // log mode if ServerInfo.Mode == "release" { isDebug = false } initBasicLogger(logLevel, logPath, isDebug) log.SetFlags(log.Lmicroseconds | log.Lshortfile | log.LstdFlags) // mysql连接 err = initDatabase("yuedong") if err != nil { fmt.Printf("database connect failed: %s\n", err) os.Exit(-1) } // 创建图片与文件目录 if runtime.GOOS == "windows" { // TODO: } else { err = initSaveDirectory(ImageInfo.BasePath + "/" + ImageInfo.OutputDir) if err != nil { fmt.Printf("creat directory error: %s", err) } } return } func initDatabase(dbname string) error { var err error //内网地址:rm-bp1rxj4r7a204ujhn.mysql.rds.aliyuncs.com //外网地址:rm-bp1rxj4r7a204ujhnio.mysql.rds.aliyuncs.com DB, err = gopkg.OpenMysqlWithConfig(gopkg.MysqlConfig{ Host: "rm-bp1cbq48ara8ex330.mysql.rds.aliyuncs.com", Port: "3306", UserName: "yuedong", Password: "Yuedong2020", Database: dbname, }) DB.SingularTable(true) return err } func initBasicLogger(logLevel string, logPath string, isDebug bool) { if _, err := os.Open(logPath); err != nil && os.IsNotExist(err) { p, _ := os.Getwd() logPath = path.Join(p, logPath) _, err = os.Create(logPath) } var js string if isDebug { js = fmt.Sprintf(`{ "level": "%s", "encoding": "json", "outputPaths": ["stdout","%s"], "errorOutputPaths": ["stdout"] }`, logLevel, logPath) } else { js = fmt.Sprintf(`{ "level": "%s", "encoding": "json", "outputPaths": ["%s"], "errorOutputPaths": ["%s"] }`, logLevel, logPath, logPath) } var cfg zap.Config if err := json.Unmarshal([]byte(js), &cfg); err != nil { panic(err) } cfg.EncoderConfig = zap.NewProductionEncoderConfig() cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder var err error Logger, err = cfg.Build() if err != nil { //Logger.Error("init logger error: ", zap.String("err", err.Error())) } else { Logger.Info("log init") _ = Logger.Sync() } } func initSaveDirectory(path string) error { _, err := os.Stat(path) if notExist := os.IsNotExist(err); notExist == true { err := os.MkdirAll(path, os.ModePerm) if err != nil { return err } } return nil }