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
55 stop: make(chan struct{}),
61 // Serve starts a new instance of the Web Server
62 func (s *WebServer) Serve() error {
66 s.router.Use(gin.Logger())
67 s.router.Use(gin.Recovery())
68 s.router.Use(s.middlewareXDSDetails())
69 s.router.Use(s.middlewareCORS())
72 s.api = NewAPIV1(s.Context)
75 s.sIOServer, err = socketio.NewServer(nil)
80 s.router.GET("/socket.io/", s.socketHandler)
81 s.router.POST("/socket.io/", s.socketHandler)
82 /* TODO: do we want to support ws://... ?
83 s.router.Handle("WS", "/socket.io/", s.socketHandler)
84 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
87 // Web Application (serve on / )
88 idxFile := path.Join(s.Config.FileConf.WebAppDir, indexFilename)
89 if _, err := os.Stat(idxFile); err != nil {
90 s.Log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
92 s.Log.Infof("Serve WEB app dir: %s", s.Config.FileConf.WebAppDir)
93 s.router.Use(static.Serve("/", static.LocalFile(s.Config.FileConf.WebAppDir, true)))
94 s.webApp = s.router.Group("/", s.serveIndexFile)
99 // Serve in the background
100 serveError := make(chan error, 1)
102 msg := fmt.Sprintf("Web Server running on localhost:%s ...\n", s.Config.FileConf.HTTPPort)
105 serveError <- http.ListenAndServe(":"+s.Config.FileConf.HTTPPort, s.router)
108 // Wait for stop, restart or error signals
111 // Shutting down permanently
113 s.Log.Infoln("shutting down (stop)")
114 case err = <-serveError:
115 // Error due to listen/serve failure
123 func (s *WebServer) Stop() {
127 // serveIndexFile provides initial file (eg. index.html) of webapp
128 func (s *WebServer) serveIndexFile(c *gin.Context) {
129 c.HTML(200, indexFilename, gin.H{})
132 // Add details in Header
133 func (s *WebServer) middlewareXDSDetails() gin.HandlerFunc {
134 return func(c *gin.Context) {
135 c.Header("XDS-Version", s.Config.Version)
136 c.Header("XDS-API-Version", s.Config.APIVersion)
142 func (s *WebServer) middlewareCORS() gin.HandlerFunc {
143 return func(c *gin.Context) {
144 if c.Request.Method == "OPTIONS" {
145 c.Header("Access-Control-Allow-Origin", "*")
146 c.Header("Access-Control-Allow-Headers", "Content-Type")
147 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
148 c.Header("Access-Control-Max-Age", cookieMaxAge)
149 c.AbortWithStatus(204)
157 // socketHandler is the handler for the "main" websocket connection
158 func (s *WebServer) socketHandler(c *gin.Context) {
160 // Retrieve user session
161 sess := s.sessions.Get(c)
163 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
167 s.sIOServer.On("connection", func(so socketio.Socket) {
168 s.Log.Debugf("WS Connected (SID=%v)", so.Id())
169 s.sessions.UpdateIOSocket(sess.ID, &so)
171 so.On("disconnection", func() {
172 s.Log.Debugf("WS disconnected (SID=%v)", so.Id())
173 s.sessions.UpdateIOSocket(sess.ID, nil)
177 s.sIOServer.On("error", func(so socketio.Socket, err error) {
178 s.Log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
181 s.sIOServer.ServeHTTP(c.Writer, c.Request)