embed-file-system.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package common
  2. import (
  3. "embed"
  4. "io/fs"
  5. "net/http"
  6. "os"
  7. "github.com/gin-contrib/static"
  8. )
  9. // Credit: https://github.com/gin-contrib/static/issues/19
  10. type embedFileSystem struct {
  11. http.FileSystem
  12. }
  13. func (e *embedFileSystem) Exists(prefix string, path string) bool {
  14. _, err := e.Open(path)
  15. if err != nil {
  16. return false
  17. }
  18. return true
  19. }
  20. func (e *embedFileSystem) Open(name string) (http.File, error) {
  21. if name == "/" {
  22. // This will make sure the index page goes to NoRouter handler,
  23. // which will use the replaced index bytes with analytic codes.
  24. return nil, os.ErrNotExist
  25. }
  26. return e.FileSystem.Open(name)
  27. }
  28. func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
  29. efs, err := fs.Sub(fsEmbed, targetPath)
  30. if err != nil {
  31. panic(err)
  32. }
  33. return &embedFileSystem{
  34. FileSystem: http.FS(efs),
  35. }
  36. }
  37. // themeAwareFileSystem delegates to the appropriate embedded FS based on
  38. // the current theme (via GetTheme). This enables runtime theme switching
  39. // without restarting the server.
  40. type themeAwareFileSystem struct {
  41. defaultFS static.ServeFileSystem
  42. classicFS static.ServeFileSystem
  43. }
  44. func (t *themeAwareFileSystem) Exists(prefix string, path string) bool {
  45. if GetTheme() == "classic" {
  46. return t.classicFS.Exists(prefix, path)
  47. }
  48. return t.defaultFS.Exists(prefix, path)
  49. }
  50. func (t *themeAwareFileSystem) Open(name string) (http.File, error) {
  51. if GetTheme() == "classic" {
  52. return t.classicFS.Open(name)
  53. }
  54. return t.defaultFS.Open(name)
  55. }
  56. func NewThemeAwareFS(defaultFS, classicFS static.ServeFileSystem) static.ServeFileSystem {
  57. return &themeAwareFileSystem{defaultFS: defaultFS, classicFS: classicFS}
  58. }