I'm serving my index.html like a static file like this:
router.StaticFile("/", "../client/dist/index.html")
It is a Vue PWA application, but i want to disable the cache for index.html because it is caching my production environment variables. The app can sometimes build the dist folder even multiple times during the day only for changing those variables and because of the service worker cache the client side does not read the new variables.
How can i prevent this from caching using the golang side ?
Comment From: depado
Using the Cache-Control Header might be what you're looking for.
Comment From: vposham
Looks like gin's staticFile API internally uses http.ServeFile which adds "last-modified" header in the response. In subsequent request (like refresh of page), browser sends "if-modified-since" request header, but it is always being ignored and responded with 304 status code.
Fixing this open Golang issue can also fix it - https://github.com/golang/go/issues/47539 - but looks like its left to the client which uses serveContent API from net/http.
Comment From: vposham
@Depado I think StaticFile API doesnt give us a way to control Cache-Control header.
Comment From: DeeCen
I used Hard-Code to fix like this:
// StaticFileFS like engine.StaticFileFS
func StaticFileFS(engine *gin.Engine, relativePath string, filepath string, fs embed.FS) gin.IRoutes {
return engine.GET(relativePath, func(ctx *gin.Context) {
ctx.Header(`Content-Type`, `xxx`)
ctx.Header(`Cache-Control`, `public, max-age=604800`)
cont, err := fs.ReadFile(filepath)
if err != nil {
_ = ctx.Error(err)
return
}
_, _ = ctx.Writer.Write(cont)
})
}