feat: add ETag header to static assets
we are adding an ETag tag based on calculating the md5 hash of the file contents
This commit is contained in:
parent
8839b646fb
commit
54cda5546a
@ -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()
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user