У меня есть веб-приложение, которое обслуживает статические файлы HTML/JS/CSS, а также имеет некоторые конечные точки API. Я заметил, что мой HTML/JS/CSS не кэшируется в браузере. Например, каждый раз, когда я перезагружаю страницу, они полностью загружаются заново.
Это изменение конфигурации на стороне сервера, которое мне нужно установить? Как я могу добиться этого с помощью Go и Gorilla Mux?
Я использую Google App Engine, поэтому Nginx невозможен.
Вот мой код main.go:
package main
import (
"associations"
"html/template"
"net/http"
"log"
"io/ioutil"
"github.com/gorilla/mux"
"github.com/rs/cors"
"google.golang.org/appengine"
"google.golang.org/appengine/mail"
)
var index = template.Must(template.ParseFiles(
"dist/index.html",
))
func init() {
r := mux.NewRouter()
r.HandleFunc("/", homeHandler)
r.HandleFunc("/api/{tenant}/certificates", associations.GetCertificate).Methods("GET")
r.HandleFunc("/api/{tenant}/requests", associations.PostRequest).Methods("POST")
// handle static files
r.PathPrefix("/static/").Handler(
http.StripPrefix("/static/", http.FileServer(http.Dir("dist/static/"))))
r.NotFoundHandler = http.HandlerFunc(homeHandler) // work around for SPA serving index.html
handler := cors.Default().Handler(r)
http.Handle("/", handler)
}
РЕДАКТИРОВАТЬ: вот решение с предложением @Topo:
// handle static files
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/",
CacheControlWrapper(http.FileServer(http.Dir("dist/static/")))))
....
func CacheControlWrapper(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=2592000") // 30 days
h.ServeHTTP(w, r)
})
}