main.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "gorm.io/driver/mysql"
  5. "gorm.io/gorm"
  6. gormLogger "gorm.io/gorm/logger"
  7. "iot_manager_service/app/data/controller"
  8. data "iot_manager_service/app/data/dao"
  9. device "iot_manager_service/app/device/dao"
  10. multimedia "iot_manager_service/app/multimedia/dao"
  11. record "iot_manager_service/app/record/dao"
  12. system "iot_manager_service/app/system/dao"
  13. "iot_manager_service/config"
  14. _ "iot_manager_service/config"
  15. "iot_manager_service/router"
  16. "iot_manager_service/util/cache"
  17. "iot_manager_service/util/logger"
  18. "iot_manager_service/util/minio"
  19. "net/url"
  20. "os"
  21. "time"
  22. )
  23. func main() {
  24. // 只在本地开调试模式
  25. if isDevEnv() {
  26. gin.SetMode(gin.DebugMode)
  27. } else {
  28. gin.SetMode(gin.ReleaseMode)
  29. }
  30. logger.InitLog()
  31. // 实例化配置
  32. initDB()
  33. err := cache.InitRedis()
  34. if err != nil {
  35. panic(err)
  36. }
  37. minio.InitMinio()
  38. controller.CalcTask()
  39. engine := gin.Default()
  40. router.InitRouter(engine)
  41. if isDevEnv() {
  42. println(gin.DebugMode + "当前为开发环境,会产生较多调试日志")
  43. } else {
  44. println(gin.ReleaseMode)
  45. }
  46. _ = engine.Run(config.Instance().Server.Address)
  47. }
  48. func initDB() {
  49. cfg := config.Instance()
  50. dsn := cfg.Database.User + ":" + cfg.Database.Password + "@tcp(" + cfg.Database.Host + ":" + cfg.Database.Port + ")/" + cfg.Database.Name + "?charset=utf8&parseTime=True" + "&loc=" + url.QueryEscape(cfg.Database.Timezone)
  51. logCfg := gormLogger.New(logger.Logger, gormLogger.Config{
  52. SlowThreshold: 200 * time.Millisecond,
  53. LogLevel: gormLogger.Info,
  54. Colorful: true,
  55. })
  56. // 如果是本地开发环境 则 打印gorm 查询日志到控制台
  57. if isDevEnv() {
  58. logCfg = gormLogger.Default
  59. }
  60. //logCfg = gormLogger.Default
  61. db, err := gorm.Open(mysql.New(mysql.Config{
  62. DSN: dsn,
  63. }), &gorm.Config{Logger: logCfg})
  64. if err != nil {
  65. panic(err)
  66. } else {
  67. sqlDB, err := db.DB()
  68. if err != nil {
  69. panic(err)
  70. }
  71. if err := sqlDB.Ping(); err != nil {
  72. panic(err)
  73. }
  74. sqlDB.SetMaxOpenConns(32)
  75. sqlDB.SetMaxOpenConns(5)
  76. }
  77. device.InitDB(db)
  78. system.InitDB(db)
  79. multimedia.InitDB(db)
  80. data.InitDB(db)
  81. record.InitDB(db)
  82. }
  83. // isDevEnv 是否开发环境 本地开发需要添加环境变量
  84. // [windows] CMD下执行 setx "DEV_ENV" "1"
  85. // [linux] export DEV_ENV="1"
  86. func isDevEnv() bool {
  87. if os.Getenv("DEV_ENV") == "1" {
  88. return true
  89. }
  90. return false
  91. }