-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathstatic.go
62 lines (56 loc) · 1.42 KB
/
static.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
package kubefilebrowser
import (
"embed"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"path"
"strings"
)
//go:embed static/*
var staticFS embed.FS
const fsBase = "static"
// StaticFile 使用go.16新的特性embed 到包前端编译后的代码. 替代nginx. one binary rules them all
func StaticFile(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 = path.Join(fsBase, urlPath)
f, err := staticFS.Open(urlPath)
if err != nil {
//NoRoute
bs, err := staticFS.ReadFile(path.Join(fsBase, "/", indexHtml))
if err != nil {
logrus.Error(err, "embed fs")
return
}
c.Status(200)
_, _ = c.Writer.Write(bs)
c.Abort()
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 := staticFS.ReadFile(urlPath)
if err != nil {
logrus.Error(err, "embed fs")
return
}
c.Status(200)
_, _ = c.Writer.Write(bs)
c.Abort()
}
}
}