embed_frontend.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package server
  2. import (
  3. "embed"
  4. "io/fs"
  5. "net/http"
  6. "github.com/labstack/echo/v4"
  7. "github.com/labstack/echo/v4/middleware"
  8. )
  9. //go:embed dist
  10. var embeddedFiles embed.FS
  11. func getFileSystem(path string) http.FileSystem {
  12. fs, err := fs.Sub(embeddedFiles, path)
  13. if err != nil {
  14. panic(err)
  15. }
  16. return http.FS(fs)
  17. }
  18. func embedFrontend(e *echo.Echo) {
  19. // Use echo static middleware to serve the built dist folder
  20. // refer: https://github.com/labstack/echo/blob/master/middleware/static.go
  21. e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
  22. Skipper: defaultAPIRequestSkipper,
  23. HTML5: true,
  24. Filesystem: getFileSystem("dist"),
  25. }))
  26. assetsGroup := e.Group("assets")
  27. assetsGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
  28. return func(c echo.Context) error {
  29. c.Response().Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
  30. return next(c)
  31. }
  32. })
  33. assetsGroup.Use(middleware.StaticWithConfig(middleware.StaticConfig{
  34. Skipper: defaultAPIRequestSkipper,
  35. HTML5: true,
  36. Filesystem: getFileSystem("dist/assets"),
  37. }))
  38. }