Skip to content

Commit

Permalink
Added cache control middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianrudnik committed Nov 1, 2023
1 parent 75ad283 commit 25458ed
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
37 changes: 37 additions & 0 deletions service/internal/webservice/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package webservice

import (
"github.com/gin-gonic/gin"
"github.com/samber/lo"
"path/filepath"
)

func CacheControl() gin.HandlerFunc {
return func(c *gin.Context) {
cacheableSuffixes := []string{
".css",
".js",
".png",
".jpg",
".jpeg",
".gif",
".ico",
".svg",
".woff",
".woff2",
".ttf",
".eot",
".otf",
}

_, found := lo.Find(cacheableSuffixes, func(prefix string) bool {
return filepath.Ext(c.Request.RequestURI) == prefix
})

if found {
c.Writer.Header().Set("Cache-Control", "public, max-age=604800, immutable")
} else {
c.Writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
}
}
}
3 changes: 2 additions & 1 deletion service/internal/webservice/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ func Serve(indexer *indexer.Search, pushChan *PushChannel, bindAddr string) erro
r := gin.New()
r.Use(gin.Recovery())
r.Use(logger.SetLogger())
r.Use(CacheControl())

r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:10000", "http://localhost:5173"},
AllowMethods: []string{"GET", "POST", "OPTIONS", "PUT", "DELETE"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Accept-Encoding"},
ExposeHeaders: []string{"Content-Length", "Content-Type", "Content-Encoding"},
ExposeHeaders: []string{"*"},
AllowCredentials: true,
AllowOriginFunc: func(origin string) bool {
return true
Expand Down

0 comments on commit 25458ed

Please sign in to comment.