summaryrefslogtreecommitdiff
path: root/web.go
blob: 508cab3feba59a4a2399c92d96cd706fe9c5626c (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
package main

import (
	"embed"
	"github.com/gin-gonic/gin"
	"io/fs"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
)

//go:embed assets
var assets embed.FS

var (
	router   *gin.Engine
	listener net.Listener
	server   = http.Server{}
)

func webSetup() {
	gin.SetMode(gin.ReleaseMode)
	if config.System.Verbose {
		gin.SetMode(gin.DebugMode)
	}

	router = gin.New()
	router.Use(recovery())
	router.ForwardedByClientIP = config.Server.Proxy
	if config.System.Verbose {
		router.Use(gin.Logger())
	}
	router.NoRoute(func(context *gin.Context) {
		context.Redirect(http.StatusTemporaryRedirect, "/web")
	})

	if config.Server.Unix {
		if l, err := net.Listen("unix", config.Server.Host); err != nil {
			log.Fatalf("error listening on socket: %s", err)
		} else {
			listener = l
		}

		if err := os.Chmod(config.Server.Host, 0777); err != nil {
			log.Printf("error chmod: %s", err)
		}

		log.Printf("web server listening on socket %s", config.Server.Host)
	} else {
		if l, err := net.Listen("tcp", config.Server.Host+":"+strconv.Itoa(int(config.Server.Port))); err != nil {
			log.Fatalf("error listening on TCP port: %s", err)
		} else {
			listener = l
		}

		log.Printf("web server listening on %s:%d", config.Server.Host, config.Server.Port)
	}
	server.Handler = router

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

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

	registerAPI()
}

func serve() {
	if err := server.Serve(listener); err == http.ErrServerClosed {
		log.Printf("web server closed")
	} else {
		log.Printf("error serve: %s", err)
	}
}