Fix static file caching (#2975)

Replaces #2972

Fixes #2483

Removed etag header as etag is used incorrectly, it should be based on
content not startup time and we don't handle it from request headers
anyway.
This commit is contained in:
Lauris BH 2023-12-20 10:31:52 +02:00 committed by GitHub
parent 5a7e314f5a
commit 6432109daf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -16,9 +16,7 @@ package web
import ( import (
"bytes" "bytes"
"crypto/md5"
"errors" "errors"
"fmt"
"io" "io"
"io/fs" "io/fs"
"net/http" "net/http"
@ -32,12 +30,7 @@ import (
"go.woodpecker-ci.org/woodpecker/v2/web" "go.woodpecker-ci.org/woodpecker/v2/web"
) )
// etag is an identifier for a resource version var indexHTML []byte
// it lets caches determine if resource is still the same and not send it again
var (
etag = fmt.Sprintf("%x", md5.Sum([]byte(time.Now().String())))
indexHTML []byte
)
type prefixFS struct { type prefixFS struct {
fs http.FileSystem fs http.FileSystem
@ -53,8 +46,6 @@ func New() (*gin.Engine, error) {
e := gin.New() e := gin.New()
indexHTML = parseIndex() indexHTML = parseIndex()
e.Use(setupCache)
rootPath := server.Config.Server.RootPath rootPath := server.Config.Server.RootPath
httpFS, err := web.HTTPFS() httpFS, err := web.HTTPFS()
@ -121,6 +112,8 @@ func serveFile(f *prefixFS) func(ctx *gin.Context) {
mime = "image/svg" mime = "image/svg"
} }
ctx.Status(http.StatusOK) ctx.Status(http.StatusOK)
ctx.Writer.Header().Set("Cache-Control", "public, max-age=31536000")
ctx.Writer.Header().Del("Expires")
ctx.Writer.Header().Set("Content-Type", mime) ctx.Writer.Header().Set("Content-Type", mime)
if _, err := ctx.Writer.Write(replaceBytes(data)); err != nil { if _, err := ctx.Writer.Write(replaceBytes(data)); err != nil {
log.Error().Err(err).Msgf("can not write %s", ctx.Request.URL.Path) log.Error().Err(err).Msgf("can not write %s", ctx.Request.URL.Path)
@ -142,6 +135,7 @@ func redirect(location string, status ...int) func(ctx *gin.Context) {
func handleIndex(c *gin.Context) { func handleIndex(c *gin.Context) {
rw := c.Writer rw := c.Writer
rw.Header().Set("Cache-Control", "no-cache")
rw.Header().Set("Content-Type", "text/html; charset=UTF-8") rw.Header().Set("Content-Type", "text/html; charset=UTF-8")
rw.WriteHeader(http.StatusOK) rw.WriteHeader(http.StatusOK)
if _, err := rw.Write(indexHTML); err != nil { if _, err := rw.Write(indexHTML); err != nil {
@ -171,9 +165,3 @@ func parseIndex() []byte {
data = bytes.ReplaceAll(data, []byte("/assets/custom.js"), []byte(server.Config.Server.RootPath+"/assets/custom.js")) data = bytes.ReplaceAll(data, []byte("/assets/custom.js"), []byte(server.Config.Server.RootPath+"/assets/custom.js"))
return data return data
} }
func setupCache(c *gin.Context) {
c.Writer.Header().Set("Cache-Control", "public, max-age=31536000")
c.Writer.Header().Del("Expires")
c.Writer.Header().Set("ETag", etag)
}