1 回答

TA貢獻1851條經驗 獲得超3個贊
假設您的文件服務器代碼類似于文檔中的示例:
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/static"))))
您可以編寫一個處理程序,通過剝離 ETag 標頭并設置Cache-Control: no-cache, private, max-age=0防止緩存(本地和上游代理)來設置適當的緩存標頭以防止這種行為:
var epoch = time.Unix(0, 0).Format(time.RFC1123)
var noCacheHeaders = map[string]string{
"Expires": epoch,
"Cache-Control": "no-cache, private, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
}
var etagHeaders = []string{
"ETag",
"If-Modified-Since",
"If-Match",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
}
func NoCache(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Delete any ETag headers that may have been set
for _, v := range etagHeaders {
if r.Header.Get(v) != "" {
r.Header.Del(v)
}
}
// Set our NoCache headers
for k, v := range noCacheHeaders {
w.Header().Set(k, v)
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
像這樣使用它:
http.Handle("/static/", NoCache(http.StripPrefix("/static/", http.FileServer(http.Dir("/static")))))
注意:我最初在github.com/zenazn/goji/middleware 上寫了這個,所以你也可以導入它,但這是一段簡單的代碼,我想為后代展示一個完整的例子!
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報