From 76f201444416c1a85a3d34d77a3f656ae574e0f9 Mon Sep 17 00:00:00 2001 From: CzBiX Date: Wed, 8 Oct 2025 23:58:22 +0800 Subject: [PATCH] feat: add http cache for static files (#395) * feat: add http cache for static files fix #392 * minor typo fix --- internal/middleware/ui_middleware.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/internal/middleware/ui_middleware.go b/internal/middleware/ui_middleware.go index ff028a1..adcb784 100644 --- a/internal/middleware/ui_middleware.go +++ b/internal/middleware/ui_middleware.go @@ -1,10 +1,12 @@ package middleware import ( + "fmt" "io/fs" "net/http" "os" "strings" + "time" "tinyauth/internal/assets" "github.com/gin-gonic/gin" @@ -27,14 +29,16 @@ func (m *UIMiddleware) Init() error { } m.uiFs = ui - m.uiFileServer = http.FileServer(http.FS(ui)) + m.uiFileServer = http.FileServerFS(ui) return nil } func (m *UIMiddleware) Middleware() gin.HandlerFunc { return func(c *gin.Context) { - switch strings.Split(c.Request.URL.Path, "/")[1] { + path := strings.TrimPrefix(c.Request.URL.Path, "/") + + switch strings.SplitN(path, "/", 2)[0] { case "api": c.Next() return @@ -42,12 +46,19 @@ func (m *UIMiddleware) Middleware() gin.HandlerFunc { c.Next() return default: - _, err := fs.Stat(m.uiFs, strings.TrimPrefix(c.Request.URL.Path, "/")) + _, err := fs.Stat(m.uiFs, path) + + // Enough for one authentication flow + maxAge := 15 * time.Minute if os.IsNotExist(err) { c.Request.URL.Path = "/" + } else if strings.HasPrefix(path, "assets/") { + // assets are named with a hash and can be cached for a long time + maxAge = 30 * 24 * time.Hour } + c.Writer.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(maxAge.Seconds()))) m.uiFileServer.ServeHTTP(c.Writer, c.Request) c.Abort() return