Add caching for static web assets

This commit is contained in:
Benedikt Kulmann
2020-11-16 23:22:56 +01:00
parent aaf9029a3e
commit 9c6dac8328
10 changed files with 50 additions and 5 deletions
+10 -1
View File
@@ -1,13 +1,16 @@
package middleware
import (
"fmt"
"net/http"
"path"
"strconv"
"strings"
"time"
)
// Static is a middleware that serves static assets.
func Static(root string, fs http.FileSystem) func(http.Handler) http.Handler {
func Static(root string, fs http.FileSystem, ttl int) func(http.Handler) http.Handler {
if !strings.HasSuffix(root, "/") {
root = root + "/"
}
@@ -19,6 +22,9 @@ func Static(root string, fs http.FileSystem) func(http.Handler) http.Handler {
),
)
// we don't have a last modification date of the static assets, so we use the service start date
lastModified := time.Now().UTC().Format(http.TimeFormat)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, path.Join(root, "api")) {
@@ -27,6 +33,9 @@ func Static(root string, fs http.FileSystem) func(http.Handler) http.Handler {
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
} else {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%s", strconv.Itoa(ttl)))
w.Header().Set("Last-Modified", lastModified)
w.Header().Del("Expires")
static.ServeHTTP(w, r)
}
}