Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix static file caching #2975

Merged
merged 2 commits into from
Dec 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@

import (
"bytes"
"crypto/md5"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
Expand All @@ -32,12 +30,7 @@
"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 @@
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 @@
mime = "image/svg"
}
ctx.Status(http.StatusOK)
ctx.Writer.Header().Set("Cache-Control", "public, max-age=31536000")
ctx.Writer.Header().Del("Expires")

Check warning on line 116 in server/web/web.go

View check run for this annotation

Codecov / codecov/patch

server/web/web.go#L115-L116

Added lines #L115 - L116 were not covered by tests
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 handleIndex(c *gin.Context) {
rw := c.Writer
rw.Header().Set("Cache-Control", "no-cache")

Check warning on line 138 in server/web/web.go

View check run for this annotation

Codecov / codecov/patch

server/web/web.go#L138

Added line #L138 was not covered by tests
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 @@
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)
}