77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gitlink.org.cn/cloudream/common/pkgs/async"
|
|
"gitlink.org.cn/cloudream/common/pkgs/logger"
|
|
hubapi "gitlink.org.cn/cloudream/jcs-pub/hub/sdk/api"
|
|
)
|
|
|
|
type ServerEventChan = async.UnboundChannel[ServerEvent]
|
|
|
|
type ServerEvent interface {
|
|
IsServerEvent() bool
|
|
}
|
|
|
|
type ExitEvent struct {
|
|
ServerEvent
|
|
Err error
|
|
}
|
|
|
|
type Server struct {
|
|
cfg *Config
|
|
httpSrv *http.Server
|
|
svc *Service
|
|
eventChan *ServerEventChan
|
|
}
|
|
|
|
func NewServer(cfg *Config, svc *Service) *Server {
|
|
return &Server{
|
|
cfg: cfg,
|
|
svc: svc,
|
|
eventChan: async.NewUnboundChannel[ServerEvent](),
|
|
}
|
|
}
|
|
|
|
func (s *Server) Start() *ServerEventChan {
|
|
go func() {
|
|
if s.cfg == nil {
|
|
return
|
|
}
|
|
|
|
engine := gin.New()
|
|
s.httpSrv = &http.Server{
|
|
Addr: s.cfg.Listen,
|
|
Handler: engine,
|
|
}
|
|
|
|
s.initRouters(engine)
|
|
|
|
logger.Infof("start serving http at: %s", s.cfg.Listen)
|
|
|
|
err := s.httpSrv.ListenAndServe()
|
|
s.eventChan.Send(ExitEvent{Err: err})
|
|
}()
|
|
return s.eventChan
|
|
}
|
|
|
|
func (s *Server) Stop() {
|
|
if s.httpSrv == nil {
|
|
s.eventChan.Send(ExitEvent{})
|
|
return
|
|
}
|
|
|
|
s.httpSrv.Shutdown(context.Background())
|
|
}
|
|
|
|
func (s *Server) initRouters(engine *gin.Engine) {
|
|
engine.GET(hubapi.GetStreamPath, s.IOSvc().GetStream)
|
|
engine.POST(hubapi.SendStreamPath, s.IOSvc().SendStream)
|
|
engine.POST(hubapi.ExecuteIOPlanPath, s.IOSvc().ExecuteIOPlan)
|
|
engine.POST(hubapi.SendVarPath, s.IOSvc().SendVar)
|
|
engine.GET(hubapi.GetVarPath, s.IOSvc().GetVar)
|
|
}
|