memos/server/embed_frontend.go

53 lines
1.2 KiB
Go
Raw Normal View History

2022-07-10 09:02:56 +08:00
package server
import (
"embed"
"io/fs"
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
2023-09-17 22:55:13 +08:00
"github.com/usememos/memos/internal/util"
2022-07-10 09:02:56 +08:00
)
//go:embed dist
var embeddedFiles embed.FS
2022-09-09 00:50:58 +08:00
func getFileSystem(path string) http.FileSystem {
fs, err := fs.Sub(embeddedFiles, path)
2022-07-10 09:02:56 +08:00
if err != nil {
panic(err)
}
return http.FS(fs)
}
func embedFrontend(e *echo.Echo) {
2022-09-09 00:50:58 +08: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 17:29:23 +08:00
Skipper: defaultAPIRequestSkipper,
HTML5: true,
2022-09-09 00:50:58 +08:00
Filesystem: getFileSystem("dist"),
}))
assetsGroup := e.Group("assets")
assetsGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
2022-09-09 00:50:58 +08: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 17:29:23 +08:00
Skipper: defaultAPIRequestSkipper,
2022-09-09 00:50:58 +08:00
HTML5: true,
Filesystem: getFileSystem("dist/assets"),
}))
2022-07-10 09:02:56 +08:00
}
2023-09-17 19:20:03 +08:00
func defaultAPIRequestSkipper(c echo.Context) bool {
path := c.Request().URL.Path
return util.HasPrefixes(path, "/api", "/memos.api.v2")
}