首页 > 解决方案 > 为所有处理程序设置标题

问题描述

现在看起来像这样

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)

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

标签: gohttp-headers

解决方案


包装多路复用器

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

而不是单独的处理程序。

请注意,当处理程序参数为 时,用作处理ListendAndServe程序。此外,并将处理程序添加到.http.DefaultServeMuxnilhttp.Handlehttp.HandleFunchttp.DefaultServeMux


推荐阅读