11 "github.com/Sirupsen/logrus"
12 "github.com/gin-contrib/static"
13 "github.com/gin-gonic/gin"
14 "github.com/googollee/go-socket.io"
18 type WebServer struct {
22 sIOServer *socketio.Server
23 webApp *gin.RouterGroup
24 stop chan struct{} // signals intentional stop
27 const indexFilename = "index.html"
29 // NewWebServer creates an instance of WebServer
30 func NewWebServer(ctx *Context) *WebServer {
32 // Setup logging for gin router
33 if ctx.Log.Level == logrus.DebugLevel {
34 gin.SetMode(gin.DebugMode)
36 gin.SetMode(gin.ReleaseMode)
39 // Redirect gin logs into another logger (LogVerboseOut may be stderr or a file)
40 gin.DefaultWriter = ctx.Config.LogVerboseOut
41 gin.DefaultErrorWriter = ctx.Config.LogVerboseOut
42 log.SetOutput(ctx.Config.LogVerboseOut)
44 // FIXME - fix pb about isTerminal=false when out is in VSC Debug Console
54 stop: make(chan struct{}),
60 // Serve starts a new instance of the Web Server
61 func (s *WebServer) Serve() error {
65 s.router.Use(gin.Logger())
66 s.router.Use(gin.Recovery())
67 s.router.Use(s.middlewareXDSDetails())
68 s.router.Use(s.middlewareCORS())
71 s.api = NewAPIV1(s.Context)
74 s.sIOServer, err = socketio.NewServer(nil)
79 s.router.GET("/socket.io/", s.socketHandler)
80 s.router.POST("/socket.io/", s.socketHandler)
81 /* TODO: do we want to support ws://... ?
82 s.router.Handle("WS", "/socket.io/", s.socketHandler)
83 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
86 // Web Application (serve on / )
87 idxFile := path.Join(s.Config.FileConf.WebAppDir, indexFilename)
88 if _, err := os.Stat(idxFile); err != nil {
89 s.Log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
91 s.Log.Infof("Serve WEB app dir: %s", s.Config.FileConf.WebAppDir)
92 s.router.Use(static.Serve("/", static.LocalFile(s.Config.FileConf.WebAppDir, true)))
93 s.webApp = s.router.Group("/", s.serveIndexFile)
98 // Serve in the background
99 serveError := make(chan error, 1)
101 msg := fmt.Sprintf("Web Server running on localhost:%s ...\n", s.Config.FileConf.HTTPPort)
104 serveError <- http.ListenAndServe(":"+s.Config.FileConf.HTTPPort, s.router)
107 // Wait for stop, restart or error signals
110 // Shutting down permanently
112 s.Log.Infoln("shutting down (stop)")
113 case err = <-serveError:
114 // Error due to listen/serve failure
122 func (s *WebServer) Stop() {
126 // serveIndexFile provides initial file (eg. index.html) of webapp
127 func (s *WebServer) serveIndexFile(c *gin.Context) {
128 c.HTML(200, indexFilename, gin.H{})
131 // Add details in Header
132 func (s *WebServer) middlewareXDSDetails() gin.HandlerFunc {
133 return func(c *gin.Context) {
134 c.Header("XDS-Version", s.Config.Version)
135 c.Header("XDS-API-Version", s.Config.APIVersion)
141 func (s *WebServer) middlewareCORS() gin.HandlerFunc {
142 return func(c *gin.Context) {
143 if c.Request.Method == "OPTIONS" {
144 c.Header("Access-Control-Allow-Origin", "*")
145 c.Header("Access-Control-Allow-Headers", "Content-Type")
146 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
147 c.Header("Access-Control-Max-Age", cookieMaxAge)
148 c.AbortWithStatus(204)
156 // socketHandler is the handler for the "main" websocket connection
157 func (s *WebServer) socketHandler(c *gin.Context) {
159 // Retrieve user session
160 sess := s.sessions.Get(c)
162 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
166 s.sIOServer.On("connection", func(so socketio.Socket) {
167 s.Log.Debugf("WS Connected (SID=%v)", so.Id())
168 s.sessions.UpdateIOSocket(sess.ID, &so)
170 so.On("disconnection", func() {
171 s.Log.Debugf("WS disconnected (SID=%v)", so.Id())
172 s.sessions.UpdateIOSocket(sess.ID, nil)
176 s.sIOServer.On("error", func(so socketio.Socket, err error) {
177 s.Log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
180 s.sIOServer.ServeHTTP(c.Writer, c.Request)