web.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package websubsvc
  2. import (
  3. "context"
  4. "git.swzry.com/zry/zry-go-program-framework/core"
  5. "github.com/gin-gonic/gin"
  6. "net/http"
  7. "time"
  8. )
  9. var _ core.ISubService = (*WebSubService)(nil)
  10. type WebSubService struct {
  11. logic IWebSubServiceLogic
  12. ginEngine *gin.Engine
  13. wctx *WebSubServiceContext
  14. httpServer *http.Server
  15. enbaleTLS bool
  16. certFile string
  17. keyFile string
  18. running bool
  19. shutdownTimeout time.Duration
  20. }
  21. type IWebSubServiceLogic interface {
  22. Prepare(ctx *WebSubServiceContext) error
  23. GetHttpServer(ctx *WebSubServiceContext) *http.Server
  24. }
  25. func NewWebSubService(logic IWebSubServiceLogic) *WebSubService {
  26. s := &WebSubService{
  27. logic: logic,
  28. ginEngine: gin.New(),
  29. running: false,
  30. shutdownTimeout: 10 * time.Second,
  31. }
  32. return s
  33. }
  34. func (w *WebSubService) Prepare(ctx *core.SubServiceContext) error {
  35. w.wctx = &WebSubServiceContext{
  36. subSvcCtx: ctx,
  37. IModuleLogger: ctx,
  38. s: w,
  39. }
  40. if ctx.GetGlobalDebugMode() {
  41. gin.SetMode(gin.DebugMode)
  42. } else {
  43. gin.SetMode(gin.ReleaseMode)
  44. }
  45. err := w.logic.Prepare(w.wctx)
  46. w.httpServer = w.logic.GetHttpServer(w.wctx)
  47. if err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. func (w *WebSubService) Run(ctx *core.SubServiceContext) error {
  53. ctx.Info("listening at: ", w.httpServer.Addr)
  54. var err error
  55. w.running = true
  56. if w.enbaleTLS {
  57. err = w.httpServer.ListenAndServeTLS(w.certFile, w.keyFile)
  58. } else {
  59. err = w.httpServer.ListenAndServe()
  60. }
  61. w.running = false
  62. if err != nil {
  63. ctx.Error("error in running web server: ", err)
  64. return err
  65. } else {
  66. ctx.Info("web server end normally")
  67. }
  68. return nil
  69. }
  70. func (w *WebSubService) Stop(ctx *core.SubServiceContext) {
  71. if w.running {
  72. sctx, cncl := context.WithTimeout(context.Background(), w.shutdownTimeout)
  73. defer cncl()
  74. err := w.httpServer.Shutdown(sctx)
  75. if err != nil {
  76. ctx.Error("error in shutting down web api server: ", err)
  77. }
  78. }
  79. }