Skip to content

Commit b886174

Browse files
chore: add server side caching
1 parent 84929da commit b886174

File tree

4 files changed

+39
-16
lines changed

4 files changed

+39
-16
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ The DIP promotes high-level modules (e.g., use cases) to depend on abstractions
7272
- HTTP Server
7373
- [x] [Echo framework](https://echo.labstack.com/)
7474
- [x] Server Side Caching
75-
- [ ] Cache but revalidate (Header `Cache-Control: no-cache`)
76-
- [ ] Set Expiration Time (Header `Cache-Control: max-age=120`)
75+
- [x] Cache but revalidate (Header `Cache-Control: no-cache`)
76+
- [x] Set Expiration Time (Header `Cache-Control: max-age=120`)
7777
- [ ] Request ID in logger (Header `X-Request-Id: xxx`)
7878
- RESTful
7979
- [x] Create Resource (`POST` verb)

internal/app/app.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ func (app *App) Start() error {
4646

4747
app.Echo.Debug = app.Cfg.Server.Debug
4848
app.Echo.Use(middleware.AppCors())
49+
app.Echo.Use(middleware.CacheWithRevalidation)
4950

5051
return app.Echo.StartServer(&http.Server{
5152
Addr: fmt.Sprintf(":%s", app.Cfg.Server.RESTPort),

pkg/middleware/cors.go

Lines changed: 0 additions & 14 deletions
This file was deleted.

pkg/middleware/echo_middleware.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package middleware
2+
3+
import (
4+
"net/http"
5+
"time"
6+
7+
"github.com/labstack/echo/v4"
8+
"github.com/labstack/echo/v4/middleware"
9+
)
10+
11+
func AppCors() echo.MiddlewareFunc {
12+
return middleware.CORSWithConfig(middleware.CORSConfig{
13+
AllowOrigins: []string{"*"}, // Specify the allowed origins or use a list of allowed domains
14+
AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
15+
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization},
16+
})
17+
}
18+
19+
func CacheWithRevalidation(next echo.HandlerFunc) echo.HandlerFunc {
20+
return func(c echo.Context) error {
21+
// Call the next handler
22+
err := next(c)
23+
24+
// Set Cache-Control header to enable caching and revalidation with a maximum age of 120 seconds
25+
c.Response().Header().Set("Cache-Control", "no-cache, max-age=120, must-revalidate")
26+
27+
// Set Expires header to a future time to indicate the expiration time
28+
expiresTime := time.Now().Add(120 * time.Second)
29+
c.Response().Header().Set("Expires", expiresTime.UTC().Format(http.TimeFormat))
30+
31+
// Set Last-Modified header to the current time
32+
c.Response().Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
33+
34+
return err
35+
}
36+
}

0 commit comments

Comments
 (0)