-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathserve.go
47 lines (42 loc) · 1.08 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
package main
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/mereith/nav/logger"
)
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) bool
}
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
fileserver := http.FileServer(fs)
if urlPrefix != "" {
fileserver = http.StripPrefix(urlPrefix, fileserver)
}
return func(c *gin.Context) {
if fs.Exists(urlPrefix, c.Request.URL.Path) {
fileserver.ServeHTTP(c.Writer, c.Request)
c.Abort()
} else {
path := c.Request.URL.Path
pathHasAPI := strings.Contains(path, "/api") && !strings.Contains(path, "/api-token")
// pathHasAdmin := strings.Contains(path, "/admin")
// pathHasLogin := strings.Contains(path, "/login")
if pathHasAPI {
return
} else {
file, err := fs.Open("index.html")
if err != nil {
logger.LogError("文件不存在: %s", c.Request.URL.Path)
return
}
defer file.Close()
// 把文件返回
http.ServeContent(c.Writer, c.Request, "index.html", time.Now(), file)
c.Abort()
}
}
}
}