Skip to content

Commit

Permalink
Fix static file caching (#2975)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lafriks authored Dec 20, 2023
1 parent 5a7e314 commit 6432109
Showing 1 changed file with 4 additions and 16 deletions.
20 changes: 4 additions & 16 deletions server/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ package web

import (
"bytes"
"crypto/md5"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
Expand All @@ -32,12 +30,7 @@ import (
"go.woodpecker-ci.org/woodpecker/v2/web"
)

// etag is an identifier for a resource version
// 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
)
var indexHTML []byte

type prefixFS struct {
fs http.FileSystem
Expand All @@ -53,8 +46,6 @@ func New() (*gin.Engine, error) {
e := gin.New()
indexHTML = parseIndex()

e.Use(setupCache)

rootPath := server.Config.Server.RootPath

httpFS, err := web.HTTPFS()
Expand Down Expand Up @@ -121,6 +112,8 @@ func serveFile(f *prefixFS) func(ctx *gin.Context) {
mime = "image/svg"
}
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)
if _, err := ctx.Writer.Write(replaceBytes(data)); err != nil {
log.Error().Err(err).Msgf("can not write %s", ctx.Request.URL.Path)
Expand All @@ -142,6 +135,7 @@ func redirect(location string, status ...int) func(ctx *gin.Context) {

func handleIndex(c *gin.Context) {
rw := c.Writer
rw.Header().Set("Cache-Control", "no-cache")
rw.Header().Set("Content-Type", "text/html; charset=UTF-8")
rw.WriteHeader(http.StatusOK)
if _, err := rw.Write(indexHTML); err != nil {
Expand Down Expand Up @@ -171,9 +165,3 @@ func parseIndex() []byte {
data = bytes.ReplaceAll(data, []byte("/assets/custom.js"), []byte(server.Config.Server.RootPath+"/assets/custom.js"))
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)
}

0 comments on commit 6432109

Please sign in to comment.