-
Notifications
You must be signed in to change notification settings - Fork 77
/
main.go
68 lines (58 loc) · 1.55 KB
/
main.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
62
63
64
65
66
67
68
package main
import (
"embed"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"path"
"path/filepath"
"strings"
)
var buildAt string
var gitHash string
func main() {
logrus.SetReportCaller(true)
r := gin.Default()
r.GET("/version", func(c *gin.Context) { c.JSON(200, gin.H{gitHash: buildAt}) })
r.Use(feMw("/")) //替换nginx serve 前端HTML代码
r.GET("/ws", ApiWsGuacamole()) //websocket proxy to guacd
r.Run(":9528")
}
//go:embed frontend/dist/*
var fs embed.FS
const fsBase = "frontend/dist" //和 embed一样
//feMw 使用go.16新的特性embed 到包前端编译后的代码. 替代nginx. one binary rules them all
func feMw(urlPrefix string) gin.HandlerFunc {
const indexHtml = "index.html"
return func(c *gin.Context) {
urlPath := strings.TrimSpace(c.Request.URL.Path)
if urlPath == urlPrefix {
urlPath = path.Join(urlPrefix, indexHtml)
}
urlPath = filepath.Join(fsBase, urlPath)
f, err := fs.Open(urlPath)
if err != nil {
return
}
fi, err := f.Stat()
if strings.HasSuffix(urlPath, ".html") {
c.Header("Cache-Control", "no-cache")
c.Header("Content-Type", "text/html; charset=utf-8")
}
if strings.HasSuffix(urlPath, ".js") {
c.Header("Content-Type", "text/javascript; charset=utf-8")
}
if strings.HasSuffix(urlPath, ".css") {
c.Header("Content-Type", "text/css; charset=utf-8")
}
if err != nil || !fi.IsDir() {
bs, err := fs.ReadFile(urlPath)
if err != nil {
logrus.WithError(err).Error("embed fs")
return
}
c.Status(200)
c.Writer.Write(bs)
c.Abort()
}
}
}