11 "github.com/Sirupsen/logrus"
12 "github.com/gin-contrib/static"
13 "github.com/gin-gonic/gin"
14 "github.com/googollee/go-socket.io"
15 "github.com/iotbzh/xds-server/lib/apiv1"
16 "github.com/iotbzh/xds-server/lib/crosssdk"
17 "github.com/iotbzh/xds-server/lib/model"
18 "github.com/iotbzh/xds-server/lib/session"
19 "github.com/iotbzh/xds-server/lib/xdsconfig"
26 sIOServer *socketio.Server
27 webApp *gin.RouterGroup
29 sessions *session.Sessions
30 mfolders *model.Folders
34 stop chan struct{} // signals intentional stop
37 const indexFilename = "index.html"
38 const cookieMaxAge = "3600"
40 // New creates an instance of Server
41 func New(cfg *xdsconfig.Config, mfolders *model.Folders, sdks *crosssdk.SDKs, logr *logrus.Logger, sillyLog bool) *Server {
43 // Setup logging for gin router
44 if logr.Level == logrus.DebugLevel {
45 gin.SetMode(gin.DebugMode)
47 gin.SetMode(gin.ReleaseMode)
50 // Redirect gin logs into another logger (LogVerboseOut may be stderr or a file)
51 gin.DefaultWriter = cfg.LogVerboseOut
52 gin.DefaultErrorWriter = cfg.LogVerboseOut
53 log.SetOutput(cfg.LogVerboseOut)
55 // FIXME - fix pb about isTerminal=false when out is in VSC Debug Console
71 stop: make(chan struct{}),
77 // Serve starts a new instance of the Web Server
78 func (s *Server) Serve() error {
82 s.router.Use(gin.Logger())
83 s.router.Use(gin.Recovery())
84 s.router.Use(s.middlewareXDSDetails())
85 s.router.Use(s.middlewareCORS())
88 s.sessions = session.NewClientSessions(s.router, s.log, cookieMaxAge, s.sillyLog)
91 s.api = apiv1.New(s.router, s.sessions, s.cfg, s.mfolders, s.sdks)
94 s.sIOServer, err = socketio.NewServer(nil)
99 s.router.GET("/socket.io/", s.socketHandler)
100 s.router.POST("/socket.io/", s.socketHandler)
101 /* TODO: do we want to support ws://... ?
102 s.router.Handle("WS", "/socket.io/", s.socketHandler)
103 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
106 // Web Application (serve on / )
107 idxFile := path.Join(s.cfg.FileConf.WebAppDir, indexFilename)
108 if _, err := os.Stat(idxFile); err != nil {
109 s.log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
111 s.log.Infof("Serve WEB app dir: %s", s.cfg.FileConf.WebAppDir)
112 s.router.Use(static.Serve("/", static.LocalFile(s.cfg.FileConf.WebAppDir, true)))
113 s.webApp = s.router.Group("/", s.serveIndexFile)
118 // Serve in the background
119 serveError := make(chan error, 1)
121 msg := fmt.Sprintf("Web Server running on localhost:%s ...\n", s.cfg.FileConf.HTTPPort)
124 serveError <- http.ListenAndServe(":"+s.cfg.FileConf.HTTPPort, s.router)
127 // Wait for stop, restart or error signals
130 // Shutting down permanently
132 s.log.Infoln("shutting down (stop)")
133 case err = <-serveError:
134 // Error due to listen/serve failure
142 func (s *Server) Stop() {
146 // serveIndexFile provides initial file (eg. index.html) of webapp
147 func (s *Server) serveIndexFile(c *gin.Context) {
148 c.HTML(200, indexFilename, gin.H{})
151 // Add details in Header
152 func (s *Server) middlewareXDSDetails() gin.HandlerFunc {
153 return func(c *gin.Context) {
154 c.Header("XDS-Version", s.cfg.Version)
155 c.Header("XDS-API-Version", s.cfg.APIVersion)
161 func (s *Server) middlewareCORS() gin.HandlerFunc {
162 return func(c *gin.Context) {
163 if c.Request.Method == "OPTIONS" {
164 c.Header("Access-Control-Allow-Origin", "*")
165 c.Header("Access-Control-Allow-Headers", "Content-Type")
166 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
167 c.Header("Access-Control-Max-Age", cookieMaxAge)
168 c.AbortWithStatus(204)
176 // socketHandler is the handler for the "main" websocket connection
177 func (s *Server) socketHandler(c *gin.Context) {
179 // Retrieve user session
180 sess := s.sessions.Get(c)
182 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
186 s.sIOServer.On("connection", func(so socketio.Socket) {
187 s.log.Debugf("WS Connected (SID=%v)", so.Id())
188 s.sessions.UpdateIOSocket(sess.ID, &so)
190 so.On("disconnection", func() {
191 s.log.Debugf("WS disconnected (SID=%v)", so.Id())
192 s.sessions.UpdateIOSocket(sess.ID, nil)
196 s.sIOServer.On("error", func(so socketio.Socket, err error) {
197 s.log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
200 s.sIOServer.ServeHTTP(c.Writer, c.Request)