server.go 4.5 KB

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