new-api/common/embed-file-system.go

44 lines
845 B
Go
Raw Normal View History

2023-04-22 20:39:27 +08:00
package common
import (
"embed"
"io/fs"
"net/http"
"os"
"github.com/gin-contrib/static"
2023-04-22 20:39:27 +08:00
)
// Credit: https://github.com/gin-contrib/static/issues/19
type embedFileSystem struct {
http.FileSystem
}
func (e *embedFileSystem) Exists(prefix string, path string) bool {
2023-04-22 20:39:27 +08:00
_, 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 gose to NoRouter handler,
// which will use the replaced index bytes with analytic codes.
return nil, os.ErrNotExist
}
return e.FileSystem.Open(name)
}
2023-04-22 20:39:27 +08:00
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
efs, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return &embedFileSystem{
2023-04-22 20:39:27 +08:00
FileSystem: http.FS(efs),
}
}