server.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package api
  2. import (
  3. "Medical_OAuth/app/admin/model"
  4. global2 "Medical_OAuth/common/global"
  5. "Medical_OAuth/common/middleware"
  6. "Medical_OAuth/common/middleware/handler"
  7. "Medical_OAuth/common/storage"
  8. "context"
  9. "fmt"
  10. "gorm.io/gorm"
  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. "Medical_OAuth/app/admin/router"
  25. ext "Medical_OAuth/conf"
  26. database "Medical_OAuth/db"
  27. )
  28. var (
  29. configYml string
  30. StartCmd = &cobra.Command{
  31. Use: "server",
  32. Short: "Start API server",
  33. Example: "Medical_OAuth 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. )
  58. database.AutoMigrateDB()
  59. //注册监听函数
  60. queue := sdk.Runtime.GetMemoryQueue("")
  61. queue.Register(global2.LoginLog, model.SaveLoginLog)
  62. queue.Register(global2.OperateLog, model.SaveOperaLog)
  63. //queue.Register(global2.ApiCheck, model.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. // fixme 新加的服务在这里配置
  81. //go func() {
  82. // otherSvc.InitJob()
  83. // otherSvc.Setup(sdk.Runtime.GetDb())
  84. //
  85. //}()
  86. // fixme 定时任务,需要时再配置
  87. //go func() {
  88. // jobs.InitJob()
  89. // jobs.Setup(sdk.Runtime.GetDb())
  90. //}()
  91. go func() {
  92. // 服务连接
  93. if config.SslConfig.Enable {
  94. if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
  95. log.Fatal("listen: ", err)
  96. }
  97. } else {
  98. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  99. log.Fatal("listen: ", err)
  100. }
  101. }
  102. }()
  103. go func() {
  104. InitService()
  105. }()
  106. tip()
  107. fmt.Println(pkg.Green("Server run at:"))
  108. fmt.Printf("- Local: http://localhost:%d/ \r\n", config.ApplicationConfig.Port)
  109. fmt.Printf("- Network: http://%s:%d/ \r\n", pkg.GetLocalHost(), config.ApplicationConfig.Port)
  110. fmt.Println(pkg.Green("Swagger run at:"))
  111. fmt.Printf("- Local: http://localhost:%d/swagger/index.html \r\n", config.ApplicationConfig.Port)
  112. fmt.Printf("- Network: http://%s:%d/swagger/index.html \r\n", pkg.GetLocalHost(), config.ApplicationConfig.Port)
  113. fmt.Printf("%s Enter Control + C Shutdown Server \r\n", pkg.GetCurrentTimeStr())
  114. // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
  115. quit := make(chan os.Signal)
  116. signal.Notify(quit, os.Interrupt)
  117. <-quit
  118. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  119. defer cancel()
  120. fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr())
  121. if err := srv.Shutdown(ctx); err != nil {
  122. log.Fatal("Server Shutdown:", err)
  123. }
  124. log.Println("Server exiting")
  125. return nil
  126. }
  127. var Router runtime.Router
  128. func tip() {
  129. usageStr := `欢迎使用 ` + pkg.Green(`OAuth `+global2.Version) + ` 可以使用 ` + pkg.Red(`-h`) + ` 查看命令`
  130. fmt.Printf("%s \n\n", usageStr)
  131. }
  132. func initRouter() {
  133. var r *gin.Engine
  134. h := sdk.Runtime.GetEngine()
  135. if h == nil {
  136. h = gin.New()
  137. sdk.Runtime.SetEngine(h)
  138. }
  139. switch h.(type) {
  140. case *gin.Engine:
  141. r = h.(*gin.Engine)
  142. default:
  143. log.Fatal("not support other engine")
  144. os.Exit(-1)
  145. }
  146. if config.SslConfig.Enable {
  147. r.Use(handler.TlsHandler())
  148. }
  149. r.Use(middleware.Sentinel()).
  150. Use(middleware.RequestId(pkg.TrafficKey)).
  151. Use(api.SetRequestLogger)
  152. middleware.InitMiddleware(r)
  153. }
  154. func InitService() {
  155. // gorm 创建或更新
  156. obj := model.SysService{}
  157. service := model.SysService{
  158. No: ext.ExtConfig.Service.Number,
  159. Name: ext.ExtConfig.Service.Name,
  160. Host: config.ApplicationConfig.Host,
  161. AuthCode: ext.ExtConfig.Service.AuthCode,
  162. }
  163. db := database.DB
  164. err := db.Where("name = ?", ext.ExtConfig.Service.Name).First(&obj).Error
  165. if err != nil {
  166. if gorm.ErrRecordNotFound == err {
  167. db.Create(&service)
  168. }
  169. } else {
  170. db.Model(&service).Where("name = ?", ext.ExtConfig.Service.Name).Updates(&service)
  171. }
  172. }