You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
2.7 KiB
Go

package services
import (
"embed"
"io"
"io/fs"
"net/http"
"strings"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
type embedFileSystem struct {
http.FileSystem
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
_, err := e.Open(path)
return err == nil
}
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
fsys, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return embedFileSystem{
FileSystem: http.FS(fsys),
}
}
func FindNextIndexFile(currentPath string, fsys static.ServeFileSystem) string {
findPath := strings.TrimSuffix(currentPath, "/")
logrus.Infoln("Finding index file for path:", findPath)
testFile := findPath + ".html"
logrus.Infoln("Checking for HTML file:", testFile)
if fsys.Exists("", testFile) {
return testFile
}
testFile = findPath + "/index.html"
logrus.Infoln("Checking for index file:", testFile)
if fsys.Exists("", testFile) {
return testFile
}
lastSlash := strings.LastIndex(findPath, "/")
if lastSlash < 0 {
return ""
}
findPath = findPath[:lastSlash]
lastSlash = strings.LastIndex(findPath, "/")
if lastSlash < 0 {
return ""
}
endfix := findPath[lastSlash+1:]
testFile = findPath + "/[" + endfix + "].html"
logrus.Infoln("Checking for dynamic route file:", testFile)
if fsys.Exists("", testFile) {
return testFile
}
return ""
}
func HandleStaticFile(f embed.FS, router *gin.Engine) {
root := EmbedFolder(f, "out")
router.Use(static.Serve("/", root))
staticServer := static.Serve("/", root)
router.NoRoute(func(c *gin.Context) {
if c.Request.Method == http.MethodGet &&
!strings.ContainsRune(c.Request.URL.Path, '.') &&
!strings.HasPrefix(c.Request.URL.Path, "/socket.io") {
logrus.Debugln("No route found for path:", c.Request.URL.Path)
// 尝试查找Next.js的index.html
indexFile := FindNextIndexFile(c.Request.URL.Path, root)
if indexFile != "" {
logrus.Infoln("Serving index file:", indexFile)
c.Request.URL.Path = indexFile
staticServer(c)
} else {
// 先读取404.html文件内容
file, err := root.Open("/404.html")
if err != nil {
logrus.Error("Failed to open 404.html:", err)
c.String(http.StatusNotFound, "404 Not Found")
return
}
defer file.Close()
// 读取文件内容
content, err := io.ReadAll(file)
if err != nil {
logrus.Error("Failed to read 404.html:", err)
c.String(http.StatusNotFound, "404 Not Found")
return
}
// 设置状态码和内容类型,然后返回内容
c.Header("Content-Type", "text/html; charset=utf-8")
c.Data(http.StatusNotFound, "text/html; charset=utf-8", content)
}
}
})
}