fs.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package web
  2. import (
  3. "embed"
  4. "io/fs"
  5. "net/http"
  6. "os"
  7. "path"
  8. )
  9. //go:embed dist
  10. var assets embed.FS
  11. //go:embed index.html
  12. var Index embed.FS
  13. // fsFunc is short-hand for constructing a http.FileSystem
  14. // implementation
  15. type fsFunc func(name string) (fs.File, error)
  16. func (f fsFunc) Open(name string) (fs.File, error) {
  17. return f(name)
  18. }
  19. // AssetsHandler returns an http.Handler that will serve files from
  20. // the Assets embed.FS. When locating a file, it will strip the given
  21. // prefix from the request and prepend the root to the filesystem
  22. // lookup: typical prefix might be /assets/, and root would be dist.
  23. func AssetsHandler(prefix, root string) http.Handler {
  24. handler := fsFunc(func(name string) (fs.File, error) {
  25. assetPath := path.Join(root, name)
  26. // If we can't find the asset, return the default index.html
  27. // content
  28. f, err := assets.Open(assetPath)
  29. if os.IsNotExist(err) {
  30. return assets.Open("dist/404.html")
  31. }
  32. // Otherwise assume this is a legitimate request routed
  33. // correctly
  34. return f, err
  35. })
  36. return http.StripPrefix(prefix, http.FileServer(http.FS(handler)))
  37. }