10 "github.com/Sirupsen/logrus"
11 "github.com/gin-contrib/static"
12 "github.com/gin-gonic/gin"
13 "github.com/googollee/go-socket.io"
14 "github.com/iotbzh/xds-server/lib/apiv1"
15 "github.com/iotbzh/xds-server/lib/crosssdk"
16 "github.com/iotbzh/xds-server/lib/model"
17 "github.com/iotbzh/xds-server/lib/session"
18 "github.com/iotbzh/xds-server/lib/xdsconfig"
25 sIOServer *socketio.Server
26 webApp *gin.RouterGroup
28 sessions *session.Sessions
32 stop chan struct{} // signals intentional stop
35 const indexFilename = "index.html"
36 const cookieMaxAge = "3600"
38 // New creates an instance of Server
39 func New(cfg *xdsconfig.Config, mfolder *model.Folder, sdks *crosssdk.SDKs, log *logrus.Logger) *Server {
41 // Setup logging for gin router
42 if log.Level == logrus.DebugLevel {
43 gin.SetMode(gin.DebugMode)
45 gin.SetMode(gin.ReleaseMode)
49 // - try to bind gin DefaultWriter & DefaultErrorWriter to logrus logger
50 // - try to fix pb about isTerminal=false when out is in VSC Debug Console
51 //gin.DefaultWriter = ??
52 //gin.DefaultErrorWriter = ??
67 stop: make(chan struct{}),
73 // Serve starts a new instance of the Web Server
74 func (s *Server) Serve() error {
78 s.router.Use(gin.Logger())
79 s.router.Use(gin.Recovery())
80 s.router.Use(s.middlewareXDSDetails())
81 s.router.Use(s.middlewareCORS())
84 s.sessions = session.NewClientSessions(s.router, s.log, cookieMaxAge)
87 s.api = apiv1.New(s.router, s.sessions, s.cfg, s.mfolder, s.sdks)
90 s.sIOServer, err = socketio.NewServer(nil)
95 s.router.GET("/socket.io/", s.socketHandler)
96 s.router.POST("/socket.io/", s.socketHandler)
97 /* TODO: do we want to support ws://... ?
98 s.router.Handle("WS", "/socket.io/", s.socketHandler)
99 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
102 // Web Application (serve on / )
103 idxFile := path.Join(s.cfg.WebAppDir, indexFilename)
104 if _, err := os.Stat(idxFile); err != nil {
105 s.log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
107 s.log.Infof("Serve WEB app dir: %s", s.cfg.WebAppDir)
108 s.router.Use(static.Serve("/", static.LocalFile(s.cfg.WebAppDir, true)))
109 s.webApp = s.router.Group("/", s.serveIndexFile)
114 // Serve in the background
115 serveError := make(chan error, 1)
117 fmt.Printf("Web Server running on localhost:%s ...\n", s.cfg.HTTPPort)
118 serveError <- http.ListenAndServe(":"+s.cfg.HTTPPort, s.router)
121 // Wait for stop, restart or error signals
124 // Shutting down permanently
126 s.log.Infoln("shutting down (stop)")
127 case err = <-serveError:
128 // Error due to listen/serve failure
136 func (s *Server) Stop() {
140 // serveIndexFile provides initial file (eg. index.html) of webapp
141 func (s *Server) serveIndexFile(c *gin.Context) {
142 c.HTML(200, indexFilename, gin.H{})
145 // Add details in Header
146 func (s *Server) middlewareXDSDetails() gin.HandlerFunc {
147 return func(c *gin.Context) {
148 c.Header("XDS-Version", s.cfg.Version)
149 c.Header("XDS-API-Version", s.cfg.APIVersion)
155 func (s *Server) middlewareCORS() gin.HandlerFunc {
156 return func(c *gin.Context) {
157 if c.Request.Method == "OPTIONS" {
158 c.Header("Access-Control-Allow-Origin", "*")
159 c.Header("Access-Control-Allow-Headers", "Content-Type")
160 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
161 c.Header("Access-Control-Max-Age", cookieMaxAge)
162 c.AbortWithStatus(204)
170 // socketHandler is the handler for the "main" websocket connection
171 func (s *Server) socketHandler(c *gin.Context) {
173 // Retrieve user session
174 sess := s.sessions.Get(c)
176 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
180 s.sIOServer.On("connection", func(so socketio.Socket) {
181 s.log.Debugf("WS Connected (SID=%v)", so.Id())
182 s.sessions.UpdateIOSocket(sess.ID, &so)
184 so.On("disconnection", func() {
185 s.log.Debugf("WS disconnected (SID=%v)", so.Id())
186 s.sessions.UpdateIOSocket(sess.ID, nil)
190 s.sIOServer.On("error", func(so socketio.Socket, err error) {
191 s.log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
194 s.sIOServer.ServeHTTP(c.Writer, c.Request)