feat: browser cache directives

This commit is contained in:
Ramires Viana
2021-04-19 12:49:40 +00:00
parent 603203848a
commit 190cb99a79
10 changed files with 41 additions and 11 deletions

View File

@@ -48,11 +48,16 @@ func (e extractor) ExtractToken(r *http.Request) (string, error) {
}
auth := r.URL.Query().Get("auth")
if auth == "" {
return "", request.ErrNoTokenInRequest
if auth != "" && strings.Count(auth, ".") == 2 {
return auth, nil
}
return auth, nil
cookie, _ := r.Cookie("auth")
if cookie != nil && strings.Count(cookie.Value, ".") == 2 {
return cookie.Value, nil
}
return "", request.ErrNoTokenInRequest
}
func withUser(fn handleFunc) handleFunc {

View File

@@ -49,7 +49,7 @@ func (d *data) Check(path string) bool {
func handle(fn handleFunc, prefix string, store *storage.Storage, server *settings.Server) http.Handler {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
settings, err := store.Settings.Get()
if err != nil {

View File

@@ -79,6 +79,11 @@ func handleImagePreview(w http.ResponseWriter, r *http.Request, imgSvc ImgServic
return errToStatus(err), err
}
isFresh := checkEtag(w, r, file.ModTime.Unix(), file.Size)
if isFresh {
return http.StatusNotModified, nil
}
cacheKey := previewCacheKey(file.Path, file.ModTime.Unix(), previewSize)
cachedFile, ok, err := fileCache.Load(r.Context(), cacheKey)
if err != nil {

View File

@@ -204,6 +204,11 @@ func rawDirHandler(w http.ResponseWriter, r *http.Request, d *data, file *files.
}
func rawFileHandler(w http.ResponseWriter, r *http.Request, file *files.FileInfo) (int, error) {
isFresh := checkEtag(w, r, file.ModTime.Unix(), file.Size)
if isFresh {
return http.StatusNotModified, nil
}
fd, err := file.Fs.Open(file.Path)
if err != nil {
return http.StatusInternalServerError, err

View File

@@ -2,6 +2,7 @@ package http
import (
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
@@ -109,6 +110,9 @@ func getStaticHandlers(store *storage.Storage, server *settings.Server, assetsFs
return http.StatusNotFound, nil
}
const maxAge = 86400 // 1 day
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", maxAge))
if d.settings.Branding.Files != "" {
if strings.HasPrefix(r.URL.Path, "img/") {
fPath := filepath.Join(d.settings.Branding.Files, r.URL.Path)

View File

@@ -3,6 +3,7 @@ package http
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
@@ -66,3 +67,11 @@ func stripPrefix(prefix string, h http.Handler) http.Handler {
h.ServeHTTP(w, r2)
})
}
func checkEtag(w http.ResponseWriter, r *http.Request, fTime, fSize int64) bool {
etag := fmt.Sprintf("%x%x", fTime, fSize)
w.Header().Set("Cache-Control", "private")
w.Header().Set("Etag", etag)
return r.Header.Get("If-None-Match") == etag
}