From 54cda5546abd693b30d1978189fcca347a6ae056 Mon Sep 17 00:00:00 2001 From: Evsyukov Denis Date: Thu, 11 Apr 2024 15:12:37 +0300 Subject: [PATCH] feat: add ETag header to static assets we are adding an ETag tag based on calculating the md5 hash of the file contents --- misc/handlers.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/misc/handlers.go b/misc/handlers.go index d097763..3e4d98d 100644 --- a/misc/handlers.go +++ b/misc/handlers.go @@ -2,12 +2,15 @@ package misc import ( + "crypto/md5" + "encoding/hex" "io" "log" "math/rand" "mime" "net/http" "path/filepath" + "strings" "github.com/gorilla/mux" @@ -141,29 +144,42 @@ var stylesheets = []string{"default.css", "custom.css"} func handlerStyle(w http.ResponseWriter, rq *http.Request) { w.Header().Set("Content-Type", mime.TypeByExtension(".css")) + hash := md5.New() + var buf strings.Builder for _, name := range stylesheets { file, err := static.FS.Open(name) if err != nil { continue } - _, err = io.Copy(w, file) + _, err = io.Copy(io.MultiWriter(&buf, hash), file) if err != nil { log.Println(err) } _ = file.Close() } + w.Header().Set("ETag", hex.EncodeToString(hash.Sum(nil))) + + _, err := io.Copy(w, strings.NewReader(buf.String())) + if err != nil { + log.Println(err) + } } func handlerRobotsTxt(w http.ResponseWriter, rq *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") - + hash := md5.New() file, err := static.FS.Open("robots.txt") if err != nil { return } + _, err = io.Copy(hash, file) + if err != nil { + log.Println(err) + } + w.Header().Set("ETag", hex.EncodeToString(hash.Sum(nil))) _, err = io.Copy(w, file) if err != nil { - log.Println() + log.Println(err) } _ = file.Close() }