teldrive/ui/ui.go

91 lines
2 KiB
Go
Raw Normal View History

2023-09-08 18:37:11 +08:00
package ui
import (
"embed"
"fmt"
"io/fs"
"net/http"
2023-09-09 13:48:46 +08:00
"path"
2023-09-08 18:37:11 +08:00
"strings"
2023-09-20 03:20:44 +08:00
"github.com/gin-contrib/gzip"
2023-09-08 18:37:11 +08:00
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
)
2023-09-10 20:17:08 +08:00
//go:embed all:teldrive-ui/dist
2023-09-08 18:37:11 +08:00
var staticFS embed.FS
func AddRoutes(router gin.IRouter) {
embeddedBuildFolder := newStaticFileSystem()
fallbackFileSystem := newFallbackFileSystem(embeddedBuildFolder)
2023-09-09 13:48:46 +08:00
router.Use(func(c *gin.Context) {
isStatic, _ := path.Match("/assets/*", c.Request.URL.Path)
isImg, _ := path.Match("/img/*", c.Request.URL.Path)
if isStatic || isImg {
c.Writer.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
2023-09-20 03:20:44 +08:00
gzip.Gzip(gzip.DefaultCompression)(c)
2023-09-09 13:48:46 +08:00
} else {
c.Writer.Header().Set("Cache-Control", "public, max-age=0, s-maxage=0, must-revalidate")
}
c.Next()
})
2023-09-08 18:37:11 +08:00
router.Use(static.Serve("/", embeddedBuildFolder))
router.Use(static.Serve("/", fallbackFileSystem))
}
type staticFileSystem struct {
http.FileSystem
}
var _ static.ServeFileSystem = (*staticFileSystem)(nil)
func newStaticFileSystem() *staticFileSystem {
sub, err := fs.Sub(staticFS, "teldrive-ui/dist")
if err != nil {
panic(err)
}
return &staticFileSystem{
FileSystem: http.FS(sub),
}
}
func (s *staticFileSystem) Exists(prefix string, path string) bool {
buildpath := fmt.Sprintf("teldrive-ui/dist%s", path)
if strings.HasSuffix(path, "/") {
_, err := staticFS.ReadDir(strings.TrimSuffix(buildpath, "/"))
return err == nil
}
f, err := staticFS.Open(buildpath)
if f != nil {
_ = f.Close()
}
return err == nil
}
type fallbackFileSystem struct {
staticFileSystem *staticFileSystem
}
var _ static.ServeFileSystem = (*fallbackFileSystem)(nil)
var _ http.FileSystem = (*fallbackFileSystem)(nil)
func newFallbackFileSystem(staticFileSystem *staticFileSystem) *fallbackFileSystem {
return &fallbackFileSystem{
staticFileSystem: staticFileSystem,
}
}
func (f *fallbackFileSystem) Open(path string) (http.File, error) {
return f.staticFileSystem.Open("/index.html")
}
func (f *fallbackFileSystem) Exists(prefix string, path string) bool {
return true
}