2 * Copyright (C) 2017-2018 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
28 "github.com/Sirupsen/logrus"
29 "github.com/gin-contrib/static"
30 "github.com/gin-gonic/gin"
31 socketio "github.com/googollee/go-socket.io"
35 type WebServer struct {
39 sIOServer *socketio.Server
40 webApp *gin.RouterGroup
41 stop chan struct{} // signals intentional stop
44 const indexFilename = "index.html"
46 // WebServerConstructor creates an instance of WebServer
47 func WebServerConstructor(ctx *Context) *WebServer {
49 // Setup logging for gin router
50 if ctx.Log.Level == logrus.DebugLevel {
51 gin.SetMode(gin.DebugMode)
53 gin.SetMode(gin.ReleaseMode)
56 // Redirect gin logs into another logger (LogVerboseOut may be stderr or a file)
57 gin.DefaultWriter = ctx.Config.LogVerboseOut
58 gin.DefaultErrorWriter = ctx.Config.LogVerboseOut
59 log.SetOutput(ctx.Config.LogVerboseOut)
61 // FIXME - fix pb about isTerminal=false when out is in VSC Debug Console
72 stop: make(chan struct{}),
78 // Serve starts a new instance of the Web Server
79 func (s *WebServer) Serve() error {
83 s.router.Use(gin.Logger())
84 s.router.Use(gin.Recovery())
85 s.router.Use(s.middlewareXDSDetails())
86 s.router.Use(s.middlewareCORS())
87 s.router.Use(s.lockRequest())
90 s.api = NewAPIV1(s.Context)
93 s.sIOServer, err = socketio.NewServer(nil)
98 s.router.GET("/socket.io/", s.socketHandler)
99 s.router.POST("/socket.io/", s.socketHandler)
100 /* TODO: do we want to support ws://... ?
101 s.router.Handle("WS", "/socket.io/", s.socketHandler)
102 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
105 // Web Application (serve on / )
106 idxFile := path.Join(s.Config.FileConf.WebAppDir, indexFilename)
107 if _, err := os.Stat(idxFile); err != nil {
108 s.Log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
110 s.Log.Infof("Serve WEB app dir: %s", s.Config.FileConf.WebAppDir)
111 s.router.Use(static.Serve("/", static.LocalFile(s.Config.FileConf.WebAppDir, true)))
112 s.webApp = s.router.Group("/", s.serveIndexFile)
117 // Serve in the background
118 serveError := make(chan error, 1)
120 msg := fmt.Sprintf("Web Server running on localhost:%s ...\n", s.Config.FileConf.HTTPPort)
123 serveError <- http.ListenAndServe(":"+s.Config.FileConf.HTTPPort, s.router)
126 // Wait for stop, restart or error signals
129 // Shutting down permanently
132 s.Log.Infoln("shutting down (stop)")
133 case err = <-serveError:
134 // Error due to listen/serve failure
142 func (s *WebServer) Stop() {
146 // serveIndexFile provides initial file (eg. index.html) of webapp
147 func (s *WebServer) serveIndexFile(c *gin.Context) {
148 c.HTML(200, indexFilename, gin.H{})
151 // Add details in Header
152 func (s *WebServer) middlewareXDSDetails() gin.HandlerFunc {
153 return func(c *gin.Context) {
154 c.Header("XDS-Version", s.Config.Version)
155 c.Header("XDS-API-Version", s.Config.APIVersion)
161 func (s *WebServer) 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 //lockRequest handles to increment/decrement xds package update
177 //to avoid updating xds-server when request is done
178 func (s *WebServer) lockRequest() gin.HandlerFunc {
179 return func(c *gin.Context) {
180 LockXdsUpdateCounter(s.Context, true)
182 LockXdsUpdateCounter(s.Context, false)
186 // socketHandler is the handler for the "main" websocket connection
187 func (s *WebServer) socketHandler(c *gin.Context) {
189 // Retrieve user session
190 sess := s.sessions.Get(c)
192 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
196 s.sIOServer.On("connection", func(so socketio.Socket) {
198 s.Log.Debugf("WS Connected (sessID=%v, SID=%v)", sessID, so.Id())
199 s.sessions.UpdateIOSocket(sessID, &so)
201 so.On("disconnection", func() {
202 s.Log.Debugf("WS disconnected (sessID=%v, SID=%v)", sessID, so.Id())
203 s.sessions.UpdateIOSocket(sess.ID, nil)
207 s.sIOServer.On("error", func(so socketio.Socket, err error) {
208 s.Log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
211 s.sIOServer.ServeHTTP(c.Writer, c.Request)