小编典典

设置所有处理程序的标头

go

现在看起来像这样

func cacheHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Cache-Control", "max-age=1800")
        h.ServeHTTP(w, r)
    })
}
http.Handle("/", cacheHandler(http.FileServer(http.Dir("./template/index"))))
http.HandleFunc("/json", sendJSONHandler)
http.HandleFunc("/contact", contactHandler)
http.Handle("/static/", http.StripPrefix("/static/", cacheHandler(http.FileServer(http.Dir("./template/static")))))
http.ListenAndServe(":80", nil)

有没有办法一次将缓存标头设置给所有处理程序?


阅读 220

收藏
2020-07-02

共1个答案

小编典典

包裹多路复用器

  http.ListenAndServe(":80", cacheHandler(http.DefaultServeMux))

而不是单个处理程序。

请注意,ListendAndServe使用http.DefaultServeMux的处理程序时的处理程序参数是nil。另外,将http.Handlehttp.HandleFunc处理程序添加到http.DefaultServeMux

2020-07-02