82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gitlink.org.cn/cloudream/common/pkgs/async"
|
|
"gitlink.org.cn/cloudream/common/pkgs/logger"
|
|
"gitlink.org.cn/cloudream/jcs-pub/client/internal/http/auth"
|
|
"gitlink.org.cn/cloudream/jcs-pub/client/internal/http/types"
|
|
v1 "gitlink.org.cn/cloudream/jcs-pub/client/internal/http/v1"
|
|
"gitlink.org.cn/cloudream/jcs-pub/client/internal/services"
|
|
"golang.org/x/net/http2"
|
|
)
|
|
|
|
type ServerEventChan = async.UnboundChannel[ServerEvent]
|
|
|
|
type ServerEvent interface {
|
|
IsServerEvent() bool
|
|
}
|
|
|
|
type ExitEvent struct {
|
|
ServerEvent
|
|
Err error
|
|
}
|
|
|
|
type Server struct {
|
|
cfg types.Config
|
|
httpSrv *http.Server
|
|
svc *services.Service
|
|
eventChan *ServerEventChan
|
|
auth *auth.Auth
|
|
v1Svr *v1.Server
|
|
}
|
|
|
|
func NewServer(cfg types.Config, svc *services.Service) *Server {
|
|
return &Server{
|
|
cfg: cfg,
|
|
svc: svc,
|
|
eventChan: async.NewUnboundChannel[ServerEvent](),
|
|
v1Svr: v1.NewServer(&cfg, svc),
|
|
}
|
|
}
|
|
|
|
func (s *Server) Start() *ServerEventChan {
|
|
go func() {
|
|
if !s.cfg.Enabled {
|
|
return
|
|
}
|
|
|
|
engine := gin.New()
|
|
s.httpSrv = &http.Server{
|
|
Addr: s.cfg.Listen,
|
|
Handler: engine,
|
|
}
|
|
s.auth = auth.New(&s.cfg)
|
|
s.httpSrv.TLSConfig = &tls.Config{
|
|
GetConfigForClient: s.auth.TLSConfigSelector,
|
|
}
|
|
http2.ConfigureServer(s.httpSrv, &http2.Server{})
|
|
|
|
s.v1Svr.InitRouters(engine.Group("/v1"), s.auth)
|
|
|
|
logger.Infof("start serving http at: %s", s.cfg.Listen)
|
|
|
|
err := s.httpSrv.ListenAndServeTLS("", "")
|
|
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())
|
|
}
|