Go set header for all handlers

喜你入骨 提交于 2019-12-24 08:57:27

问题


For now it looks like this

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)

Is there way to set cache header to all handlers at one time?


回答1:


Wrap the mux

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

instead of the individual handlers.

Note that ListendAndServe uses http.DefaultServeMux as the handler when the handler argument is nil. Also, the http.Handle and http.HandleFunc add handlers to http.DefaultServeMux.



来源:https://stackoverflow.com/questions/50889810/go-set-header-for-all-handlers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!