server.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package api
  2. import (
  3. "cold-logistics/app/admin/model"
  4. "cold-logistics/common/file_store"
  5. global2 "cold-logistics/common/global"
  6. "cold-logistics/common/middleware"
  7. "cold-logistics/common/middleware/handler"
  8. "cold-logistics/common/nats"
  9. "cold-logistics/common/storage"
  10. "context"
  11. "fmt"
  12. "log"
  13. "net/http"
  14. "os"
  15. "os/signal"
  16. "time"
  17. "github.com/gin-gonic/gin"
  18. "github.com/spf13/cobra"
  19. "gogs.baozhida.cn/zoie/OAuth-core/api"
  20. "gogs.baozhida.cn/zoie/OAuth-core/config/source/file"
  21. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  22. "gogs.baozhida.cn/zoie/OAuth-core/runtime"
  23. "gogs.baozhida.cn/zoie/OAuth-core/sdk"
  24. "gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
  25. "cold-logistics/app/admin/router"
  26. ext "cold-logistics/conf"
  27. database "cold-logistics/db"
  28. )
  29. var (
  30. configYml string
  31. StartCmd = &cobra.Command{
  32. Use: "server",
  33. Short: "Start API server",
  34. Example: "cold-logistics server -c conf/settings.yml",
  35. SilenceUsage: true,
  36. PreRun: func(cmd *cobra.Command, args []string) {
  37. setup()
  38. },
  39. RunE: func(cmd *cobra.Command, args []string) error {
  40. return run()
  41. },
  42. }
  43. )
  44. var AppRouters = make([]func(), 0)
  45. func init() {
  46. StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
  47. //注册路由
  48. AppRouters = append(AppRouters, router.InitRouter)
  49. }
  50. func setup() {
  51. // 注入配置扩展项
  52. config.ExtendConfig = &ext.ExtConfig
  53. //1. 读取配置
  54. config.Setup(
  55. file.NewSource(file.WithPath(configYml)),
  56. database.Setup,
  57. storage.Setup,
  58. file_store.QiniuSetup,
  59. nats.Setup,
  60. )
  61. database.AutoMigrateDB()
  62. //注册监听函数
  63. queue := sdk.Runtime.GetMemoryQueue("")
  64. queue.Register(global2.LoginLog, model.SaveLoginLog)
  65. queue.Register(global2.OperateLog, model.SaveOperaLog)
  66. //queue.Register(global2.ApiCheck, model.SaveSysApi)
  67. go queue.Run()
  68. usageStr := `starting api server...`
  69. log.Println(usageStr)
  70. }
  71. func run() error {
  72. if config.ApplicationConfig.Mode == pkg.ModeProd.String() {
  73. gin.SetMode(gin.ReleaseMode)
  74. }
  75. initRouter()
  76. for _, f := range AppRouters {
  77. f()
  78. }
  79. srv := &http.Server{
  80. Addr: fmt.Sprintf("%s:%d", config.ApplicationConfig.Host, config.ApplicationConfig.Port),
  81. Handler: sdk.Runtime.GetEngine(),
  82. }
  83. // fixme 新加的服务在这里配置
  84. //go func() {
  85. // otherSvc.InitJob()
  86. // otherSvc.Setup(sdk.Runtime.GetDb())
  87. //
  88. //}()
  89. // fixme 定时任务,需要时再配置
  90. //go func() {
  91. // jobs.InitJob()
  92. // jobs.Setup(sdk.Runtime.GetDb())
  93. //}()
  94. go func() {
  95. // 服务连接
  96. if config.SslConfig.Enable {
  97. if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
  98. log.Fatal("listen: ", err)
  99. }
  100. } else {
  101. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  102. log.Fatal("listen: ", err)
  103. }
  104. }
  105. }()
  106. //go func() {
  107. // InitService()
  108. //}()
  109. tip()
  110. fmt.Println(pkg.Green("Server run at:"))
  111. fmt.Printf("- Local: http://localhost:%d/ \r\n", config.ApplicationConfig.Port)
  112. fmt.Printf("- Network: http://%s:%d/ \r\n", pkg.GetLocalHost(), config.ApplicationConfig.Port)
  113. fmt.Println(pkg.Green("Swagger run at:"))
  114. fmt.Printf("- Local: http://localhost:%d/swagger/index.html \r\n", config.ApplicationConfig.Port)
  115. fmt.Printf("- Network: http://%s:%d/swagger/index.html \r\n", pkg.GetLocalHost(), config.ApplicationConfig.Port)
  116. fmt.Printf("%s Enter Control + C Shutdown Server \r\n", pkg.GetCurrentTimeStr())
  117. // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
  118. quit := make(chan os.Signal)
  119. signal.Notify(quit, os.Interrupt)
  120. <-quit
  121. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  122. defer cancel()
  123. fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr())
  124. if err := srv.Shutdown(ctx); err != nil {
  125. log.Fatal("Server Shutdown:", err)
  126. }
  127. log.Println("Server exiting")
  128. return nil
  129. }
  130. var Router runtime.Router
  131. func tip() {
  132. usageStr := `欢迎使用 ` + pkg.Green(`OAuth `+global2.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令`
  133. fmt.Printf("%s \n\n", usageStr)
  134. }
  135. func initRouter() {
  136. var r *gin.Engine
  137. h := sdk.Runtime.GetEngine()
  138. if h == nil {
  139. h = gin.New()
  140. sdk.Runtime.SetEngine(h)
  141. }
  142. switch h.(type) {
  143. case *gin.Engine:
  144. r = h.(*gin.Engine)
  145. default:
  146. log.Fatal("not support other engine")
  147. os.Exit(-1)
  148. }
  149. if config.SslConfig.Enable {
  150. r.Use(handler.TlsHandler())
  151. }
  152. r.Use(middleware.Sentinel()).
  153. Use(middleware.RequestId(pkg.TrafficKey)).
  154. Use(api.SetRequestLogger)
  155. middleware.InitMiddleware(r)
  156. }