9 "github.com/Sirupsen/logrus"
10 "github.com/gin-contrib/static"
11 "github.com/gin-gonic/gin"
12 "github.com/googollee/go-socket.io"
13 "github.com/iotbzh/xds-server/lib/apiv1"
14 "github.com/iotbzh/xds-server/lib/session"
15 "github.com/iotbzh/xds-server/lib/xdsconfig"
19 type ServerService struct {
22 sIOServer *socketio.Server
23 webApp *gin.RouterGroup
25 sessions *session.Sessions
27 stop chan struct{} // signals intentional stop
30 const indexFilename = "index.html"
31 const cookieMaxAge = "3600"
33 // NewServer creates an instance of ServerService
34 func NewServer(cfg xdsconfig.Config) *ServerService {
36 // Setup logging for gin router
37 if cfg.Log.Level == logrus.DebugLevel {
38 gin.SetMode(gin.DebugMode)
40 gin.SetMode(gin.ReleaseMode)
44 // - try to bind gin DefaultWriter & DefaultErrorWriter to logrus logger
45 // - try to fix pb about isTerminal=false when out is in VSC Debug Console
46 //gin.DefaultWriter = ??
47 //gin.DefaultErrorWriter = ??
52 svr := &ServerService{
60 stop: make(chan struct{}),
66 // Serve starts a new instance of the Web Server
67 func (s *ServerService) Serve() error {
71 s.router.Use(gin.Logger())
72 s.router.Use(gin.Recovery())
73 s.router.Use(s.middlewareXDSDetails())
74 s.router.Use(s.middlewareCORS())
77 s.sessions = session.NewClientSessions(s.router, s.log, cookieMaxAge)
80 s.api = apiv1.New(s.sessions, s.cfg, s.router)
83 s.sIOServer, err = socketio.NewServer(nil)
88 s.router.GET("/socket.io/", s.socketHandler)
89 s.router.POST("/socket.io/", s.socketHandler)
90 /* TODO: do we want to support ws://... ?
91 s.router.Handle("WS", "/socket.io/", s.socketHandler)
92 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
95 // Web Application (serve on / )
96 idxFile := path.Join(s.cfg.WebAppDir, indexFilename)
97 if _, err := os.Stat(idxFile); err != nil {
98 s.log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
100 s.log.Infof("Serve WEB app dir: %s", s.cfg.WebAppDir)
101 s.router.Use(static.Serve("/", static.LocalFile(s.cfg.WebAppDir, true)))
102 s.webApp = s.router.Group("/", s.serveIndexFile)
107 // Serve in the background
108 serveError := make(chan error, 1)
110 serveError <- http.ListenAndServe(":"+s.cfg.HTTPPort, s.router)
113 // Wait for stop, restart or error signals
116 // Shutting down permanently
118 s.log.Infoln("shutting down (stop)")
119 case err = <-serveError:
120 // Error due to listen/serve failure
128 func (s *ServerService) Stop() {
132 // serveIndexFile provides initial file (eg. index.html) of webapp
133 func (s *ServerService) serveIndexFile(c *gin.Context) {
134 c.HTML(200, indexFilename, gin.H{})
137 // Add details in Header
138 func (s *ServerService) middlewareXDSDetails() gin.HandlerFunc {
139 return func(c *gin.Context) {
140 c.Header("XDS-Version", s.cfg.Version)
141 c.Header("XDS-API-Version", s.cfg.APIVersion)
147 func (s *ServerService) middlewareCORS() gin.HandlerFunc {
148 return func(c *gin.Context) {
150 if c.Request.Method == "OPTIONS" {
151 c.Header("Access-Control-Allow-Origin", "*")
152 c.Header("Access-Control-Allow-Headers", "Content-Type")
153 c.Header("Access-Control-Allow-Methods", "POST, DELETE, GET, PUT")
154 c.Header("Content-Type", "application/json")
155 c.Header("Access-Control-Max-Age", cookieMaxAge)
156 c.AbortWithStatus(204)
164 // socketHandler is the handler for the "main" websocket connection
165 func (s *ServerService) socketHandler(c *gin.Context) {
167 // Retrieve user session
168 sess := s.sessions.Get(c)
170 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
174 s.sIOServer.On("connection", func(so socketio.Socket) {
175 s.log.Debugf("WS Connected (SID=%v)", so.Id())
176 s.sessions.UpdateIOSocket(sess.ID, &so)
178 so.On("disconnection", func() {
179 s.log.Debugf("WS disconnected (SID=%v)", so.Id())
180 s.sessions.UpdateIOSocket(sess.ID, nil)
184 s.sIOServer.On("error", func(so socketio.Socket, err error) {
185 s.log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
188 s.sIOServer.ServeHTTP(c.Writer, c.Request)