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/model"
15 "github.com/iotbzh/xds-server/lib/session"
16 "github.com/iotbzh/xds-server/lib/xdsconfig"
20 type ServerService struct {
23 sIOServer *socketio.Server
24 webApp *gin.RouterGroup
26 sessions *session.Sessions
29 stop chan struct{} // signals intentional stop
32 const indexFilename = "index.html"
33 const cookieMaxAge = "3600"
35 // NewServer creates an instance of ServerService
36 func NewServer(cfg *xdsconfig.Config, mfolder *model.Folder, log *logrus.Logger) *ServerService {
38 // Setup logging for gin router
39 if cfg.Log.Level == logrus.DebugLevel {
40 gin.SetMode(gin.DebugMode)
42 gin.SetMode(gin.ReleaseMode)
46 // - try to bind gin DefaultWriter & DefaultErrorWriter to logrus logger
47 // - try to fix pb about isTerminal=false when out is in VSC Debug Console
48 //gin.DefaultWriter = ??
49 //gin.DefaultErrorWriter = ??
54 svr := &ServerService{
63 stop: make(chan struct{}),
69 // Serve starts a new instance of the Web Server
70 func (s *ServerService) Serve() error {
74 s.router.Use(gin.Logger())
75 s.router.Use(gin.Recovery())
76 s.router.Use(s.middlewareXDSDetails())
77 s.router.Use(s.middlewareCORS())
80 s.sessions = session.NewClientSessions(s.router, s.log, cookieMaxAge)
83 s.api = apiv1.New(s.sessions, s.cfg, s.mfolder, s.router)
86 s.sIOServer, err = socketio.NewServer(nil)
91 s.router.GET("/socket.io/", s.socketHandler)
92 s.router.POST("/socket.io/", s.socketHandler)
93 /* TODO: do we want to support ws://... ?
94 s.router.Handle("WS", "/socket.io/", s.socketHandler)
95 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
98 // Web Application (serve on / )
99 idxFile := path.Join(s.cfg.WebAppDir, indexFilename)
100 if _, err := os.Stat(idxFile); err != nil {
101 s.log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
103 s.log.Infof("Serve WEB app dir: %s", s.cfg.WebAppDir)
104 s.router.Use(static.Serve("/", static.LocalFile(s.cfg.WebAppDir, true)))
105 s.webApp = s.router.Group("/", s.serveIndexFile)
110 // Serve in the background
111 serveError := make(chan error, 1)
113 serveError <- http.ListenAndServe(":"+s.cfg.HTTPPort, s.router)
116 // Wait for stop, restart or error signals
119 // Shutting down permanently
121 s.log.Infoln("shutting down (stop)")
122 case err = <-serveError:
123 // Error due to listen/serve failure
131 func (s *ServerService) Stop() {
135 // serveIndexFile provides initial file (eg. index.html) of webapp
136 func (s *ServerService) serveIndexFile(c *gin.Context) {
137 c.HTML(200, indexFilename, gin.H{})
140 // Add details in Header
141 func (s *ServerService) middlewareXDSDetails() gin.HandlerFunc {
142 return func(c *gin.Context) {
143 c.Header("XDS-Version", s.cfg.Version)
144 c.Header("XDS-API-Version", s.cfg.APIVersion)
150 func (s *ServerService) middlewareCORS() gin.HandlerFunc {
151 return func(c *gin.Context) {
153 if c.Request.Method == "OPTIONS" {
154 c.Header("Access-Control-Allow-Origin", "*")
155 c.Header("Access-Control-Allow-Headers", "Content-Type")
156 c.Header("Access-Control-Allow-Methods", "POST, DELETE, GET, PUT")
157 c.Header("Content-Type", "application/json")
158 c.Header("Access-Control-Max-Age", cookieMaxAge)
159 c.AbortWithStatus(204)
167 // socketHandler is the handler for the "main" websocket connection
168 func (s *ServerService) socketHandler(c *gin.Context) {
170 // Retrieve user session
171 sess := s.sessions.Get(c)
173 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
177 s.sIOServer.On("connection", func(so socketio.Socket) {
178 s.log.Debugf("WS Connected (SID=%v)", so.Id())
179 s.sessions.UpdateIOSocket(sess.ID, &so)
181 so.On("disconnection", func() {
182 s.log.Debugf("WS disconnected (SID=%v)", so.Id())
183 s.sessions.UpdateIOSocket(sess.ID, nil)
187 s.sIOServer.On("error", func(so socketio.Socket, err error) {
188 s.log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
191 s.sIOServer.ServeHTTP(c.Writer, c.Request)