saasitone/pkg/middleware/cache.go

23 lines
496 B
Go
Raw Normal View History

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
"github.com/labstack/echo/v4"
)
2021-12-21 17:49:05 -08:00
// CacheControl sets a Cache-Control header with a given max age
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(ctx echo.Context) error {
2021-12-03 05:18:40 -08:00
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
}
ctx.Response().Header().Set("Cache-Control", v)
return next(ctx)
2021-12-03 05:18:40 -08:00
}
}
}