memos/server/embed_frontend.go

53 lines
1.2 KiB
Go
Raw Normal View History

2022-07-10 04:02:56 +03:00
package server
import (
"embed"
"io/fs"
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
2023-09-17 17:55:13 +03:00
"github.com/usememos/memos/internal/util"
2022-07-10 04:02:56 +03:00
)
//go:embed dist
var embeddedFiles embed.FS
2022-09-08 19:50:58 +03:00
func getFileSystem(path string) http.FileSystem {
fs, err := fs.Sub(embeddedFiles, path)
2022-07-10 04:02:56 +03:00
if err != nil {
panic(err)
}
return http.FS(fs)
}
func embedFrontend(e *echo.Echo) {
2022-09-08 19:50:58 +03:00
// Use echo static middleware to serve the built dist folder
// refer: https://github.com/labstack/echo/blob/master/middleware/static.go
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
2023-02-12 12:29:23 +03:00
Skipper: defaultAPIRequestSkipper,
HTML5: true,
2022-09-08 19:50:58 +03:00
Filesystem: getFileSystem("dist"),
}))
assetsGroup := e.Group("assets")
assetsGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
2022-09-08 19:50:58 +03:00
return func(c echo.Context) error {
c.Response().Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
return next(c)
}
})
assetsGroup.Use(middleware.StaticWithConfig(middleware.StaticConfig{
2023-02-12 12:29:23 +03:00
Skipper: defaultAPIRequestSkipper,
2022-09-08 19:50:58 +03:00
HTML5: true,
Filesystem: getFileSystem("dist/assets"),
}))
2022-07-10 04:02:56 +03:00
}
2023-09-17 14:20:03 +03:00
func defaultAPIRequestSkipper(c echo.Context) bool {
path := c.Request().URL.Path
return util.HasPrefixes(path, "/api", "/memos.api.v2")
}