server.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package api
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/go-admin-team/go-admin-core/config/source/file"
  12. "github.com/go-admin-team/go-admin-core/sdk"
  13. "github.com/go-admin-team/go-admin-core/sdk/config"
  14. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  15. "github.com/go-admin-team/go-admin-core/sdk/runtime"
  16. "github.com/spf13/cobra"
  17. "git.cestong.com.cn/cecf/config-center-server/app/admin/models"
  18. "git.cestong.com.cn/cecf/config-center-server/app/admin/router"
  19. "git.cestong.com.cn/cecf/config-center-server/app/jobs"
  20. "git.cestong.com.cn/cecf/config-center-server/common/database"
  21. "git.cestong.com.cn/cecf/config-center-server/common/global"
  22. common "git.cestong.com.cn/cecf/config-center-server/common/middleware"
  23. "git.cestong.com.cn/cecf/config-center-server/common/middleware/handler"
  24. "git.cestong.com.cn/cecf/config-center-server/common/storage"
  25. ext "git.cestong.com.cn/cecf/config-center-server/config"
  26. )
  27. var (
  28. configYml string
  29. apiCheck bool
  30. StartCmd = &cobra.Command{
  31. Use: "server",
  32. Short: "Start API server",
  33. Example: "go-admin server -c config/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. StartCmd.PersistentFlags().BoolVarP(&apiCheck, "api", "a", false, "Start server with check api data")
  47. //注册路由 fixme 其他应用的路由,在本目录新建文件放在init方法
  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. )
  59. //注册监听函数
  60. queue := sdk.Runtime.GetMemoryQueue("")
  61. queue.Register(global.LoginLog, models.SaveLoginLog)
  62. queue.Register(global.OperateLog, models.SaveOperaLog)
  63. queue.Register(global.ApiCheck, models.SaveSysApi)
  64. go queue.Run()
  65. usageStr := `starting api server...`
  66. log.Println(usageStr)
  67. }
  68. func run() error {
  69. if config.ApplicationConfig.Mode == pkg.ModeProd.String() {
  70. gin.SetMode(gin.ReleaseMode)
  71. }
  72. initRouter()
  73. for _, f := range AppRouters {
  74. f()
  75. }
  76. srv := &http.Server{
  77. Addr: fmt.Sprintf("%s:%d", config.ApplicationConfig.Host, config.ApplicationConfig.Port),
  78. Handler: sdk.Runtime.GetEngine(),
  79. }
  80. go func() {
  81. jobs.InitJob()
  82. jobs.Setup(sdk.Runtime.GetDb())
  83. }()
  84. if apiCheck {
  85. var routers = sdk.Runtime.GetRouter()
  86. q := sdk.Runtime.GetMemoryQueue("")
  87. mp := make(map[string]interface{}, 0)
  88. mp["List"] = routers
  89. message, err := sdk.Runtime.GetStreamMessage("", global.ApiCheck, mp)
  90. if err != nil {
  91. log.Printf("GetStreamMessage error, %s \n", err.Error())
  92. //日志报错错误,不中断请求
  93. } else {
  94. err = q.Append(message)
  95. if err != nil {
  96. log.Printf("Append message error, %s \n", err.Error())
  97. }
  98. }
  99. }
  100. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  101. defer cancel()
  102. go func() {
  103. // 服务连接
  104. if config.SslConfig.Enable {
  105. if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
  106. log.Fatal("listen: ", err)
  107. }
  108. } else {
  109. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  110. log.Fatal("listen: ", err)
  111. }
  112. }
  113. }()
  114. fmt.Println(pkg.Red(string(global.LogoContent)))
  115. tip()
  116. fmt.Println(pkg.Green("Server run at:"))
  117. fmt.Printf("- Local: http://localhost:%d/ \r\n", config.ApplicationConfig.Port)
  118. fmt.Printf("- Network: http://%s:%d/ \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port)
  119. fmt.Println(pkg.Green("Swagger run at:"))
  120. fmt.Printf("- Local: http://localhost:%d/swagger/index.html \r\n", config.ApplicationConfig.Port)
  121. fmt.Printf("- Network: http://%s:%d/swagger/index.html \r\n", pkg.GetLocaHonst(), config.ApplicationConfig.Port)
  122. fmt.Printf("%s Enter Control + C Shutdown Server \r\n", pkg.GetCurrentTimeStr())
  123. // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
  124. quit := make(chan os.Signal)
  125. signal.Notify(quit, os.Interrupt)
  126. <-quit
  127. fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr())
  128. if err := srv.Shutdown(ctx); err != nil {
  129. log.Fatal("Server Shutdown:", err)
  130. }
  131. log.Println("Server exiting")
  132. return nil
  133. }
  134. var Router runtime.Router
  135. func tip() {
  136. usageStr := `欢迎使用 ` + pkg.Green(`go-admin `+global.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令`
  137. fmt.Printf("%s \n\n", usageStr)
  138. }
  139. func initRouter() {
  140. var r *gin.Engine
  141. h := sdk.Runtime.GetEngine()
  142. if h == nil {
  143. h = gin.New()
  144. sdk.Runtime.SetEngine(h)
  145. }
  146. switch h.(type) {
  147. case *gin.Engine:
  148. r = h.(*gin.Engine)
  149. default:
  150. log.Fatal("not support other engine")
  151. os.Exit(-1)
  152. }
  153. if config.SslConfig.Enable {
  154. r.Use(handler.TlsHandler())
  155. }
  156. //r.Use(middleware.Metrics())
  157. r.Use(common.Sentinel()).
  158. Use(common.RequestId(pkg.TrafficKey))
  159. common.InitMiddleware(r)
  160. }