123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package websubsvc
- import (
- "context"
- "git.swzry.com/zry/zry-go-program-framework/core"
- "github.com/gin-gonic/gin"
- "net/http"
- "time"
- )
- var _ core.ISubService = (*WebSubService)(nil)
- type WebSubService struct {
- logic IWebSubServiceLogic
- ginEngine *gin.Engine
- wctx *WebSubServiceContext
- httpServer *http.Server
- enbaleTLS bool
- certFile string
- keyFile string
- running bool
- shutdownTimeout time.Duration
- }
- type IWebSubServiceLogic interface {
- Prepare(ctx *WebSubServiceContext) error
- GetHttpServer(ctx *WebSubServiceContext) *http.Server
- }
- func NewWebSubService(logic IWebSubServiceLogic) *WebSubService {
- s := &WebSubService{
- logic: logic,
- ginEngine: gin.New(),
- running: false,
- shutdownTimeout: 10 * time.Second,
- }
- return s
- }
- func (w *WebSubService) Prepare(ctx *core.SubServiceContext) error {
- w.wctx = &WebSubServiceContext{
- subSvcCtx: ctx,
- IModuleLogger: ctx,
- s: w,
- }
- if ctx.GetGlobalDebugMode() {
- gin.SetMode(gin.DebugMode)
- } else {
- gin.SetMode(gin.ReleaseMode)
- }
- err := w.logic.Prepare(w.wctx)
- w.httpServer = w.logic.GetHttpServer(w.wctx)
- if err != nil {
- return err
- }
- return nil
- }
- func (w *WebSubService) Run(ctx *core.SubServiceContext) error {
- ctx.Info("listening at: ", w.httpServer.Addr)
- var err error
- w.running = true
- if w.enbaleTLS {
- err = w.httpServer.ListenAndServeTLS(w.certFile, w.keyFile)
- } else {
- err = w.httpServer.ListenAndServe()
- }
- w.running = false
- if err != nil {
- ctx.Error("error in running web server: ", err)
- return err
- } else {
- ctx.Info("web server end normally")
- }
- return nil
- }
- func (w *WebSubService) Stop(ctx *core.SubServiceContext) {
- if w.running {
- sctx, cncl := context.WithTimeout(context.Background(), w.shutdownTimeout)
- defer cncl()
- err := w.httpServer.Shutdown(sctx)
- if err != nil {
- ctx.Error("error in shutting down web api server: ", err)
- }
- }
- }
|