summaryrefslogtreecommitdiff
path: root/web.go
blob: 9f754a229c694bbfd33deca93ace6e1a10b63f91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main

import (
	"embed"
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"io/fs"
	"net"
	"net/http"
	"os"
	"strconv"
	"syscall"
)

//go:embed assets
var assets embed.FS

var (
	router   *gin.Engine
	listener net.Listener
)

func webSetup() {
	// Set log level according to
	if log.GetLevel() == log.DebugLevel {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	// Configure gin router
	router = gin.New()
	router.Use(recovery())
	router.ForwardedByClientIP = viper.GetStringMap("server")["proxy"].(bool)

	// Configure logger
	if log.GetLevel() == log.DebugLevel {
		router.Use(gin.LoggerWithWriter(logger{}))
	}

	// Register error page
	router.NoRoute(func(context *gin.Context) {
		context.JSON(http.StatusNotFound, gin.H{
			"error": "no such file or directory",
		})
	})
}

func listenerSetup() {
	var err error
	switch serverConfig["unix"].(bool) {
	case false:
		address := fmt.Sprintf("%s:%s",
			serverConfig["host"].(string),
			strconv.Itoa(int(serverConfig["port"].(int64))))
		listener, err = net.Listen("tcp", address)
		if err != nil {
			log.Errorf("Error binding %s, %s", address, err)
		}
		log.Infof("Web server listening on %s.", address)
	case true:
		path := serverConfig["host"].(string)
		listener, err = net.Listen("unix", path)
		if err != nil {
			log.Errorf("Error binding %s, %s", path, err)
		}

		err = syscall.Chmod(path, 0777)
		if err != nil {
			log.Errorf("Error changing permission of web server socket, %s", err)
		}

		log.Infof("Web server listening on unix socket %s.", path)
	}

	// Configure server
	server.Handler = router
}

func runWebServer() {
	err := server.Serve(listener)
	if err == http.ErrServerClosed {
		log.Info("Web server closed.")
	} else {
		log.Errorf("Error starting server, %s", err)
	}
}

func registerWebpage() {
	router.GET("/", func(context *gin.Context) {
		context.Redirect(http.StatusTemporaryRedirect, "web")
	})

	if stat, err := os.Stat("assets"); err == nil && stat.IsDir() {
		log.Info("Serving web interface from filesystem.")
		router.Static("/web", "assets")
	} else {
		log.Info("Serving bundled assets.")
		var public fs.FS
		public, err = fs.Sub(assets, "assets")
		if err != nil {
			log.Fatalf("Error getting subdirectory, %s", err)
		}
		router.StaticFS("/web", http.FS(public))
	}
}