fs.go 1.1 KB

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