【发布时间】:2018-07-30 06:54:20
【问题描述】:
我有一个 go web 应用程序,它提供静态 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)
})
}
【问题讨论】: