2021-12-03 05:18:40 -08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-12-06 11:53:28 -08:00
|
|
|
"time"
|
2021-12-03 05:18:40 -08:00
|
|
|
|
2021-12-07 18:36:57 -08:00
|
|
|
"github.com/eko/gocache/v2/cache"
|
|
|
|
"github.com/eko/gocache/v2/marshaler"
|
|
|
|
"github.com/go-redis/redis/v8"
|
2021-12-03 05:18:40 -08:00
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
)
|
|
|
|
|
2021-12-07 18:36:57 -08:00
|
|
|
type CachedPage struct {
|
|
|
|
URL string
|
|
|
|
HTML []byte
|
|
|
|
StatusCode int
|
|
|
|
Headers map[string]string
|
|
|
|
}
|
|
|
|
|
|
|
|
func PageCache(ch *cache.Cache) echo.MiddlewareFunc {
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2021-12-08 18:55:30 -08:00
|
|
|
res, err := marshaler.New(ch).Get(c.Request().Context(), c.Request().URL.String(), new(CachedPage))
|
2021-12-07 18:36:57 -08:00
|
|
|
if err != nil {
|
|
|
|
if err == redis.Nil {
|
2021-12-08 18:55:30 -08:00
|
|
|
c.Logger().Infof("no cached page found")
|
2021-12-07 18:36:57 -08:00
|
|
|
} else {
|
2021-12-08 18:55:30 -08:00
|
|
|
c.Logger().Errorf("failed getting cached page: %v", err)
|
2021-12-07 18:36:57 -08:00
|
|
|
}
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
|
2021-12-08 15:58:55 -08:00
|
|
|
page, ok := res.(*CachedPage)
|
|
|
|
if !ok {
|
2021-12-08 18:55:30 -08:00
|
|
|
c.Logger().Errorf("failed casting cached page")
|
2021-12-08 15:58:55 -08:00
|
|
|
return next(c)
|
|
|
|
}
|
2021-12-07 18:36:57 -08:00
|
|
|
|
|
|
|
if page.Headers != nil {
|
|
|
|
for k, v := range page.Headers {
|
|
|
|
c.Response().Header().Set(k, v)
|
|
|
|
}
|
|
|
|
}
|
2021-12-08 18:55:30 -08:00
|
|
|
c.Logger().Infof("serving cached page")
|
2021-12-07 18:36:57 -08:00
|
|
|
|
|
|
|
return c.HTMLBlob(page.StatusCode, page.HTML)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-06 11:53:28 -08:00
|
|
|
func CacheControl(maxAge time.Duration) echo.MiddlewareFunc {
|
2021-12-03 05:18:40 -08:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
|
|
|
v := "no-cache, no-store"
|
|
|
|
if maxAge > 0 {
|
2021-12-06 11:53:28 -08:00
|
|
|
v = fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds())
|
2021-12-03 05:18:40 -08:00
|
|
|
}
|
|
|
|
c.Response().Header().Set("Cache-Control", v)
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|