gobrowser-cachego-ginstatic-files

Cache Control in StaticFS server in Gin Web Framework (Golang)


I am working on an Open Source Go project using Gin Framework. I'm using embedded Templates and Static files for building the executable binaries. Since the static files are embedded, they are not going to change but the static files are not being cached and every subsequent page refresh results in HTTP Status 200 for the static CSS. The documentation was not really helpful in fixing the problem.

Please suggest if I'm missing out on something. How can this be fixed?

Static file server:

//go:embed templates/tailwind/*
var templateFS embed.FS

//go:embed templates/static/*
var staticFiles embed.FS


gin.SetMode(gin.ReleaseMode)
r := gin.Default()
tmpl := template.Must(template.ParseFS(templateFS, "templates/tailwind/*"))
r.SetHTMLTemplate(tmpl)
fs, _ := io.Sub(staticFiles, "templates/static")
r.StaticFS("/static/", http.FS(fs))

Also, I've tried Firefox, Chrome, Safari, and Chrome(Mobile) with Cache enabled

Go version 1.22.5 Gin version 1.10.0

GitHub Repo


Solution

  • I solved this by adding cache control headers which were not there by default in the StaticFS server.

    Updated Server:

    //go:embed templates/tailwind/*
    var templateFS embed.FS
    
    //go:embed templates/static/*
    var staticFiles embed.FS
    
    
    gin.SetMode(gin.ReleaseMode)
    r := gin.Default()
    tmpl := template.Must(template.ParseFS(templateFS, "templates/tailwind/*"))
    r.SetHTMLTemplate(tmpl)
    static := r.Group("/")
    {
        static.Use(cacheMiddleware())
        fs, _ := io.Sub(staticFiles, "templates/static")
        static.StaticFS("/static/", http.FS(fs))
    }
    

    Middleware:

    func cacheMiddleware() gin.HandlerFunc {
        return func(c *gin.Context) {
            c.Writer.Header().Set("Cache-Control", "public, max-age=604800, immutable")
        }
    }