memos/server/router/frontend/frontend.go

65 lines
1.6 KiB
Go
Raw Normal View History

package frontend
2022-07-10 09:02:56 +08:00
import (
2023-12-23 17:58:49 +08:00
"context"
2024-04-27 00:22:27 +08:00
"embed"
"io/fs"
2022-07-10 09:02:56 +08:00
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
2024-01-29 19:17:25 +08:00
"github.com/usememos/memos/internal/util"
2023-12-15 07:32:49 +08:00
"github.com/usememos/memos/server/profile"
"github.com/usememos/memos/store"
2022-07-10 09:02:56 +08:00
)
2024-04-27 00:22:27 +08:00
//go:embed dist
var embeddedFiles embed.FS
2023-12-15 07:32:49 +08:00
type FrontendService struct {
Profile *profile.Profile
Store *store.Store
}
func NewFrontendService(profile *profile.Profile, store *store.Store) *FrontendService {
return &FrontendService{
Profile: profile,
Store: store,
}
}
2024-05-30 07:23:16 +08:00
func (*FrontendService) Serve(_ context.Context, e *echo.Echo) {
2024-04-30 22:06:34 +08:00
skipper := func(c echo.Context) bool {
2024-05-30 07:19:38 +08:00
return util.HasPrefixes(c.Path(), "/api", "/memos.api.v1")
2024-04-30 22:06:34 +08:00
}
2023-12-23 08:35:54 +08:00
// Use echo static middleware to serve the built dist folder.
2024-04-28 08:36:33 +08:00
// Reference: https://github.com/labstack/echo/blob/master/middleware/static.go
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
2024-04-27 00:22:27 +08:00
HTML5: true,
Filesystem: getFileSystem("dist"),
2024-04-30 22:06:34 +08:00
Skipper: skipper,
}))
2024-04-28 08:36:33 +08:00
// Use echo gzip middleware to compress the response.
// Reference: https://echo.labstack.com/docs/middleware/gzip
2024-05-30 07:19:38 +08:00
e.Group("assets").Use(middleware.GzipWithConfig(middleware.GzipConfig{
2024-04-28 08:36:33 +08:00
Level: 5,
2024-05-30 07:19:38 +08:00
}), func(next echo.HandlerFunc) echo.HandlerFunc {
2024-04-28 08:36:33 +08:00
return func(c echo.Context) error {
c.Response().Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
return next(c)
}
2024-05-30 07:19:38 +08:00
}, middleware.StaticWithConfig(middleware.StaticConfig{
2024-04-28 08:36:33 +08:00
Filesystem: getFileSystem("dist/assets"),
}))
}
2024-04-27 00:22:27 +08:00
func getFileSystem(path string) http.FileSystem {
fs, err := fs.Sub(embeddedFiles, path)
if err != nil {
panic(err)
}
return http.FS(fs)
}