main.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "context"
  4. "designs/bootstrap"
  5. "designs/global"
  6. "designs/utils"
  7. "fmt"
  8. "github.com/gin-gonic/gin"
  9. "net/http"
  10. "path/filepath"
  11. )
  12. func init() {
  13. fmt.Printf("初始化")
  14. }
  15. func main() {
  16. //创建一个服务
  17. gin.SetMode(gin.ReleaseMode)
  18. ginServer := gin.Default()
  19. // 初始化配置
  20. bootstrap.InitializeConfig(filepath.Join(global.App.PwdPath, ".env"))
  21. //config.PrintConfig()
  22. // 初始化日志
  23. global.App.Log, global.App.LogWriter = bootstrap.InitializeLog()
  24. //跨域
  25. ginServer.Use(Cors())
  26. // 初始化Redis
  27. global.Init.InitRedisFunc = bootstrap.InitializeRedis
  28. global.App.Redis = bootstrap.InitializeRedis()
  29. // 初始化facade
  30. global.InitFacade()
  31. //服务器端口
  32. //ginServer.Run(":" + config.Get("app.port")) /*默认是8080*/
  33. // 初始化数据库
  34. global.App.DB = &utils.WtDB{DB: bootstrap.InitializeDB()}
  35. // 程序关闭前,释放数据库连接
  36. defer func() {
  37. if global.App.DB != nil {
  38. db, _ := global.App.DB.DB.DB()
  39. db.Close()
  40. }
  41. }()
  42. //初始化mongodb
  43. global.App.MongoDB = bootstrap.InitializeMongo()
  44. defer func() {
  45. if global.App.MongoDB != nil {
  46. global.App.MongoDB.Disconnect(context.Background())
  47. }
  48. }()
  49. bootstrap.InitializeCron()
  50. bootstrap.RunServer()
  51. // ginServer.RunTLS(":443", "your_certificate.crt", "your_private_key.key")
  52. }
  53. /* 跨域 */
  54. func Cors() gin.HandlerFunc {
  55. return func(context *gin.Context) {
  56. method := context.Request.Method
  57. context.Header("Access-Control-Allow-Origin", "*")
  58. context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
  59. context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
  60. context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  61. context.Header("Access-Control-Allow-Credentials", "true")
  62. if method == "OPTIONS" {
  63. context.AbortWithStatus(http.StatusNoContent)
  64. }
  65. }
  66. }