-
-
Notifications
You must be signed in to change notification settings - Fork 645
/
serve.go
61 lines (51 loc) · 1.53 KB
/
serve.go
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
package ui
import (
"embed"
"encoding/json"
"io/fs"
"net/http"
"strings"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/gotify/server/v2/model"
)
//go:embed build/*
var box embed.FS
type uiConfig struct {
Register bool `json:"register"`
Version model.VersionInfo `json:"version"`
}
// Register registers the ui on the root path.
func Register(r *gin.Engine, version model.VersionInfo, register bool) {
uiConfigBytes, err := json.Marshal(uiConfig{Version: version, Register: register})
if err != nil {
panic(err)
}
replaceConfig := func(content string) string {
return strings.Replace(content, "%CONFIG%", string(uiConfigBytes), 1)
}
ui := r.Group("/", gzip.Gzip(gzip.DefaultCompression))
ui.GET("/", serveFile("index.html", "text/html", replaceConfig))
ui.GET("/index.html", serveFile("index.html", "text/html", replaceConfig))
ui.GET("/manifest.json", serveFile("manifest.json", "application/json", noop))
ui.GET("/asset-manifest.json", serveFile("asset-manifest.json", "application/json", noop))
subBox, err := fs.Sub(box, "build")
if err != nil {
panic(err)
}
ui.GET("/static/*any", gin.WrapH(http.FileServer(http.FS(subBox))))
}
func noop(s string) string {
return s
}
func serveFile(name, contentType string, convert func(string) string) gin.HandlerFunc {
content, err := box.ReadFile("build/" + name)
if err != nil {
panic(err)
}
converted := convert(string(content))
return func(ctx *gin.Context) {
ctx.Header("Content-Type", contentType)
ctx.String(200, converted)
}
}