我有一个Go Web应用程序,它提供静态的HTML / JS / CSS文件和一些API端点。我发现我的HTML / JS / CSS没有被浏览器缓存。例如,每次重新加载页面时,它们都会被完全重新下载。
这是需要在服务器端进行配置更改吗?如何使用Go和Gorilla Mux完成此操作?
我正在使用Google App Engine,因此Nginx不可行。
下面是我的main.go代码:
这是需要在服务器端进行配置更改吗?如何使用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)
})
}
/static/js/app.3df99dd891ed2460b6bc.js
,因此我认为对于我来说不需要etag部分,但是知道这一点很好。 - user1527312if err == nil
而不是!=
。 - Phani Rithvij