Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions middleware/cache.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
package middleware

import (
"strings"

"github.com/gin-gonic/gin"
)

func Cache() func(c *gin.Context) {
return func(c *gin.Context) {
if c.Request.RequestURI == "/" {
c.Header("Cache-Control", "no-cache")
path := c.Request.URL.Path
if isStaticAsset(path) {
c.Header("Cache-Control", "max-age=604800")
} else {
c.Header("Cache-Control", "max-age=604800") // one week
c.Header("Cache-Control", "no-cache")
}
c.Header("Cache-Version", "b688f2fb5be447c25e5aa3bd063087a83db32a288bf6a4f35f2d8db310e40b14")
c.Next()
}
}

func isStaticAsset(path string) bool {
if path == "/" {
return false
}
staticExtensions := []string{".js", ".css", ".woff", ".woff2", ".ttf", ".eot",
".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".map", ".webmanifest"}
for _, ext := range staticExtensions {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
}
Comment on lines +22 to +34
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation of isStaticAsset performs a linear search through a slice on every request, which is inefficient ($O(N)$). Additionally, it is case-sensitive, meaning extensions like .JS or .CSS will not be recognized as static assets, leading to suboptimal caching for those files.

Using a switch statement on the file extension is more idiomatic in Go, provides better performance, and allows for easy case-insensitive matching.

func isStaticAsset(path string) bool {
	dot := strings.LastIndexByte(path, '.')
	if dot == -1 {
		return false
	}
	ext := strings.ToLower(path[dot:])
	switch ext {
	case ".js", ".css", ".woff", ".woff2", ".ttf", ".eot", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".map", ".webmanifest":
		return true
	}
	return false
}

Loading