server.go 4.4 KB

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