Files
new-api/common/embed-file-system.go
T
admin e83ec743c8
Docker Build / Build and Push Docker Image (push) Failing after 1m35s
feat: add DaisyUI frontend theme and document management system
2026-06-13 01:36:06 +08:00

79 lines
1.8 KiB
Go

package common
import (
"embed"
"io/fs"
"net/http"
"os"
"github.com/gin-contrib/static"
)
// Credit: https://github.com/gin-contrib/static/issues/19
type embedFileSystem struct {
http.FileSystem
}
func (e *embedFileSystem) Exists(prefix string, path string) bool {
_, err := e.Open(path)
if err != nil {
return false
}
return true
}
func (e *embedFileSystem) Open(name string) (http.File, error) {
if name == "/" {
// This will make sure the index page goes to NoRouter handler,
// which will use the replaced index bytes with analytic codes.
return nil, os.ErrNotExist
}
return e.FileSystem.Open(name)
}
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
efs, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return &embedFileSystem{
FileSystem: http.FS(efs),
}
}
// themeAwareFileSystem delegates to the appropriate embedded FS based on
// the current theme (via GetTheme). This enables runtime theme switching
// without restarting the server.
type themeAwareFileSystem struct {
defaultFS static.ServeFileSystem
classicFS static.ServeFileSystem
daisyFS static.ServeFileSystem
}
func (t *themeAwareFileSystem) Exists(prefix string, path string) bool {
switch GetTheme() {
case "classic":
return t.classicFS.Exists(prefix, path)
case "daisy":
return t.daisyFS.Exists(prefix, path)
default:
return t.defaultFS.Exists(prefix, path)
}
}
func (t *themeAwareFileSystem) Open(name string) (http.File, error) {
switch GetTheme() {
case "classic":
return t.classicFS.Open(name)
case "daisy":
return t.daisyFS.Open(name)
default:
return t.defaultFS.Open(name)
}
}
func NewThemeAwareFS(defaultFS, classicFS, daisyFS static.ServeFileSystem) static.ServeFileSystem {
return &themeAwareFileSystem{defaultFS: defaultFS, classicFS: classicFS, daisyFS: daisyFS}
}