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())
89 s.api = NewAPIV1(s.Context)
92 s.sIOServer, err = socketio.NewServer(nil)
97 s.router.GET("/socket.io/", s.socketHandler)
98 s.router.POST("/socket.io/", s.socketHandler)
99 /* TODO: do we want to support ws://... ?
100 s.router.Handle("WS", "/socket.io/", s.socketHandler)
101 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
104 // Web Application (serve on / )
105 idxFile := path.Join(s.Config.FileConf.WebAppDir, indexFilename)
106 if _, err := os.Stat(idxFile); err != nil {
107 s.Log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
109 s.Log.Infof("Serve WEB app dir: %s", s.Config.FileConf.WebAppDir)
110 s.router.Use(static.Serve("/", static.LocalFile(s.Config.FileConf.WebAppDir, true)))
111 s.webApp = s.router.Group("/", s.serveIndexFile)
116 // Serve in the background
117 serveError := make(chan error, 1)
119 msg := fmt.Sprintf("Web Server running on localhost:%s ...\n", s.Config.FileConf.HTTPPort)
122 serveError <- http.ListenAndServe(":"+s.Config.FileConf.HTTPPort, s.router)
125 // Wait for stop, restart or error signals
128 // Shutting down permanently
131 s.Log.Infoln("shutting down (stop)")
132 case err = <-serveError:
133 // Error due to listen/serve failure
141 func (s *WebServer) Stop() {
145 // serveIndexFile provides initial file (eg. index.html) of webapp
146 func (s *WebServer) serveIndexFile(c *gin.Context) {
147 c.HTML(200, indexFilename, gin.H{})
150 // Add details in Header
151 func (s *WebServer) middlewareXDSDetails() gin.HandlerFunc {
152 return func(c *gin.Context) {
153 c.Header("XDS-Version", s.Config.Version)
154 c.Header("XDS-API-Version", s.Config.APIVersion)
160 func (s *WebServer) middlewareCORS() gin.HandlerFunc {
161 return func(c *gin.Context) {
162 if c.Request.Method == "OPTIONS" {
163 c.Header("Access-Control-Allow-Origin", "*")
164 c.Header("Access-Control-Allow-Headers", "Content-Type")
165 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
166 c.Header("Access-Control-Max-Age", cookieMaxAge)
167 c.AbortWithStatus(204)
175 // socketHandler is the handler for the "main" websocket connection
176 func (s *WebServer) socketHandler(c *gin.Context) {
178 // Retrieve user session
179 sess := s.sessions.Get(c)
181 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
185 s.sIOServer.On("connection", func(so socketio.Socket) {
187 s.Log.Debugf("WS Connected (sessID=%v, SID=%v)", sessID, so.Id())
188 s.sessions.UpdateIOSocket(sessID, &so)
190 so.On("disconnection", func() {
191 s.Log.Debugf("WS disconnected (sessID=%v, SID=%v)", sessID, 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)