config.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package common
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. _ "github.com/jinzhu/gorm/dialects/mssql"
  6. _ "github.com/jinzhu/gorm/dialects/mysql"
  7. "go.uber.org/zap"
  8. "go.uber.org/zap/zapcore"
  9. gopkg "gopkg"
  10. "gopkg.in/yaml.v2"
  11. "io/ioutil"
  12. "log"
  13. "os"
  14. "path"
  15. "runtime"
  16. "time"
  17. )
  18. //serverModel get server information from config.yml
  19. type serverModel struct {
  20. Mode string `yaml:"mode"` // run mode
  21. Host string `yaml:"host"` // server host
  22. Port string `yaml:"port"` // server port
  23. EnableHttps bool `yaml:"enable_https"` // enable https
  24. CertFile string `yaml:"cert_file"` // cert file path
  25. KeyFile string `yaml:"key_file"` // key file path
  26. JwtPubKeyPath string `yaml:"jwt_public_key_path"` // jwt public key path
  27. JwtPriKeyPath string `yaml:"jwt_private_key_path"` // jwt private key path
  28. TokenExpireSecond time.Duration `yaml:"token_expire_second"` // token expire second
  29. }
  30. //databaseModel get database information from config.yml
  31. type databaseModel struct {
  32. DBType string `yaml:"type"` // db type
  33. Host string `yaml:"host"` // db host
  34. Port int `yaml:"port"` // db port
  35. UserName string `yaml:"username"` // user name
  36. Password string `yaml:"password"` // password
  37. Database string `yaml:"database"` // database
  38. MaxIdle int `yaml:"max_idle"` // db max idle connections
  39. MaxOpen int `yaml:"max_open"` // db max open connections
  40. }
  41. //redisModel get redis information from config.yml
  42. type redisModel struct {
  43. Host string `yaml:"host"`
  44. Port int `yaml:"port"`
  45. }
  46. //logModel get log information from config.yml
  47. type logModel struct {
  48. Open bool `yaml:"open"`
  49. Mode string `yaml:"mode"`
  50. Path string `yaml:"file"`
  51. Level string `yaml:"level"`
  52. }
  53. //imageModel get image information from config.yml
  54. type imageModel struct {
  55. BasePath string `yaml:"base_path"`
  56. OutputDir string `yaml:"output_dir"`
  57. PrefixURL string `yaml:"prefix_url"`
  58. MaxSize int64 `yaml:"max_size"`
  59. }
  60. //systemModel get system information from config.yml
  61. type systemModel struct {
  62. Avatar string `yaml:"avatar"`
  63. Sync bool `yaml:"sync"`
  64. Valid bool `yaml:"valid"`
  65. }
  66. type configModel struct {
  67. Server *serverModel `yaml:"server"`
  68. Database *databaseModel `yaml:"database"`
  69. Redis *redisModel `yaml:"redis"`
  70. Image *imageModel `yaml:"image"`
  71. Log *logModel `yaml:"log"`
  72. System *systemModel `yaml:"system"`
  73. }
  74. // LoadConfigInformation load config information for application
  75. func LoadConfigInformation(configPath string) (err error) {
  76. var (
  77. filePath string
  78. wr string
  79. )
  80. if configPath == "" {
  81. wr, _ = os.Getwd()
  82. wr = path.Join(wr, "conf")
  83. } else {
  84. wr = configPath
  85. }
  86. filePath = path.Join(wr, "config.yml")
  87. configData, err := ioutil.ReadFile(filePath)
  88. if err != nil {
  89. fmt.Printf(" config file read failed: %s", err)
  90. os.Exit(-1)
  91. }
  92. err = yaml.Unmarshal(configData, &ConfigInfo)
  93. if err != nil {
  94. fmt.Printf(" config parse failed: %s", err)
  95. os.Exit(-1)
  96. }
  97. // server information
  98. ServerInfo = ConfigInfo.Server
  99. // image information
  100. ImageInfo = ConfigInfo.Image
  101. // log information
  102. LoggerInfo = ConfigInfo.Log
  103. // system information
  104. SystemInfo = ConfigInfo.System
  105. // log config load
  106. logPath := LoggerInfo.Path //log path
  107. logLevel := LoggerInfo.Level // log level
  108. isDebug := true // log mode
  109. if ServerInfo.Mode == "release" {
  110. isDebug = false
  111. }
  112. initBasicLogger(logLevel, logPath, isDebug)
  113. log.SetFlags(log.Lmicroseconds | log.Lshortfile | log.LstdFlags)
  114. // mysql连接
  115. err = initDatabase("yuedong")
  116. if err != nil {
  117. fmt.Printf("database connect failed: %s\n", err)
  118. os.Exit(-1)
  119. }
  120. // 创建图片与文件目录
  121. if runtime.GOOS == "windows" {
  122. // TODO:
  123. } else {
  124. err = initSaveDirectory(ImageInfo.BasePath + "/" + ImageInfo.OutputDir)
  125. if err != nil {
  126. fmt.Printf("creat directory error: %s", err)
  127. }
  128. }
  129. return
  130. }
  131. func initDatabase(dbname string) error {
  132. var err error
  133. //内网地址:rm-bp1rxj4r7a204ujhn.mysql.rds.aliyuncs.com
  134. //外网地址:rm-bp1rxj4r7a204ujhnio.mysql.rds.aliyuncs.com
  135. DB, err = gopkg.OpenMysqlWithConfig(gopkg.MysqlConfig{
  136. Host: "rm-bp1cbq48ara8ex330.mysql.rds.aliyuncs.com",
  137. Port: "3306",
  138. UserName: "yuedong",
  139. Password: "Yuedong2020",
  140. Database: dbname,
  141. })
  142. DB.SingularTable(true)
  143. return err
  144. }
  145. func initBasicLogger(logLevel string, logPath string, isDebug bool) {
  146. if _, err := os.Open(logPath); err != nil && os.IsNotExist(err) {
  147. p, _ := os.Getwd()
  148. logPath = path.Join(p, logPath)
  149. _, err = os.Create(logPath)
  150. }
  151. var js string
  152. if isDebug {
  153. js = fmt.Sprintf(`{
  154. "level": "%s",
  155. "encoding": "json",
  156. "outputPaths": ["stdout","%s"],
  157. "errorOutputPaths": ["stdout"]
  158. }`, logLevel, logPath)
  159. } else {
  160. js = fmt.Sprintf(`{
  161. "level": "%s",
  162. "encoding": "json",
  163. "outputPaths": ["%s"],
  164. "errorOutputPaths": ["%s"]
  165. }`, logLevel, logPath, logPath)
  166. }
  167. var cfg zap.Config
  168. if err := json.Unmarshal([]byte(js), &cfg); err != nil {
  169. panic(err)
  170. }
  171. cfg.EncoderConfig = zap.NewProductionEncoderConfig()
  172. cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
  173. var err error
  174. Logger, err = cfg.Build()
  175. if err != nil {
  176. //Logger.Error("init logger error: ", zap.String("err", err.Error()))
  177. } else {
  178. Logger.Info("log init")
  179. _ = Logger.Sync()
  180. }
  181. }
  182. func initSaveDirectory(path string) error {
  183. _, err := os.Stat(path)
  184. if notExist := os.IsNotExist(err); notExist == true {
  185. err := os.MkdirAll(path, os.ModePerm)
  186. if err != nil {
  187. return err
  188. }
  189. }
  190. return nil
  191. }