embed-file-system.go 883 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // requested subtree cannot be opened.
  29. func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem {
  30. efs, err := fs.Sub(fsEmbed, targetPath)
  31. if err != nil {
  32. panic(err)
  33. }
  34. return &embedFileSystem{
  35. FileSystem: http.FS(efs),
  36. }
  37. }