frontend.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package frontend
  2. import (
  3. "context"
  4. "embed"
  5. "io/fs"
  6. "net/http"
  7. "github.com/labstack/echo/v4"
  8. "github.com/labstack/echo/v4/middleware"
  9. "github.com/usememos/memos/internal/util"
  10. "github.com/usememos/memos/server/profile"
  11. "github.com/usememos/memos/store"
  12. )
  13. //go:embed dist
  14. var embeddedFiles embed.FS
  15. type FrontendService struct {
  16. Profile *profile.Profile
  17. Store *store.Store
  18. }
  19. func NewFrontendService(profile *profile.Profile, store *store.Store) *FrontendService {
  20. return &FrontendService{
  21. Profile: profile,
  22. Store: store,
  23. }
  24. }
  25. func (*FrontendService) Serve(_ context.Context, e *echo.Echo) {
  26. skipper := func(c echo.Context) bool {
  27. return util.HasPrefixes(c.Path(), "/api", "/memos.api.v1")
  28. }
  29. // Use echo static middleware to serve the built dist folder.
  30. // Reference: https://github.com/labstack/echo/blob/master/middleware/static.go
  31. e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
  32. HTML5: true,
  33. Filesystem: getFileSystem("dist"),
  34. Skipper: skipper,
  35. }))
  36. // Use echo gzip middleware to compress the response.
  37. // Reference: https://echo.labstack.com/docs/middleware/gzip
  38. e.Group("assets").Use(middleware.GzipWithConfig(middleware.GzipConfig{
  39. Level: 5,
  40. }), func(next echo.HandlerFunc) echo.HandlerFunc {
  41. return func(c echo.Context) error {
  42. c.Response().Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
  43. return next(c)
  44. }
  45. }, middleware.StaticWithConfig(middleware.StaticConfig{
  46. Filesystem: getFileSystem("dist/assets"),
  47. }))
  48. }
  49. func getFileSystem(path string) http.FileSystem {
  50. fs, err := fs.Sub(embeddedFiles, path)
  51. if err != nil {
  52. panic(err)
  53. }
  54. return http.FS(fs)
  55. }