2 * Copyright (C) 2017 "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 "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 // NewWebServer creates an instance of WebServer
47 func NewWebServer(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
130 s.Log.Infoln("shutting down (stop)")
131 case err = <-serveError:
132 // Error due to listen/serve failure
140 func (s *WebServer) Stop() {
144 // serveIndexFile provides initial file (eg. index.html) of webapp
145 func (s *WebServer) serveIndexFile(c *gin.Context) {
146 c.HTML(200, indexFilename, gin.H{})
149 // Add details in Header
150 func (s *WebServer) middlewareXDSDetails() gin.HandlerFunc {
151 return func(c *gin.Context) {
152 c.Header("XDS-Version", s.Config.Version)
153 c.Header("XDS-API-Version", s.Config.APIVersion)
159 func (s *WebServer) middlewareCORS() gin.HandlerFunc {
160 return func(c *gin.Context) {
161 if c.Request.Method == "OPTIONS" {
162 c.Header("Access-Control-Allow-Origin", "*")
163 c.Header("Access-Control-Allow-Headers", "Content-Type")
164 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
165 c.Header("Access-Control-Max-Age", cookieMaxAge)
166 c.AbortWithStatus(204)
174 // socketHandler is the handler for the "main" websocket connection
175 func (s *WebServer) socketHandler(c *gin.Context) {
177 // Retrieve user session
178 sess := s.sessions.Get(c)
180 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
184 s.sIOServer.On("connection", func(so socketio.Socket) {
185 s.Log.Debugf("WS Connected (SID=%v)", so.Id())
186 s.sessions.UpdateIOSocket(sess.ID, &so)
188 so.On("disconnection", func() {
189 s.Log.Debugf("WS disconnected (SID=%v)", so.Id())
190 s.sessions.UpdateIOSocket(sess.ID, nil)
194 s.sIOServer.On("error", func(so socketio.Socket, err error) {
195 s.Log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
198 s.sIOServer.ServeHTTP(c.Writer, c.Request)