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)
有没有办法一次为所有处理程序设置缓存头?
解决方案
包装多路复用器
http.ListenAndServe(":80", cacheHandler(http.DefaultServeMux))
而不是单独的处理程序。
请注意,当处理程序参数为 时,用作处理ListendAndServe
程序。此外,并将处理程序添加到.http.DefaultServeMux
nil
http.Handle
http.HandleFunc
http.DefaultServeMux
推荐阅读
- mysql - 如何安全地修改大量 MySQL 列注释?
- c# - 是否有获取设备使用哪种小时格式(12/24)的通用方法?
- c++ - 我在哪里可以找到 graphviz 的 graph.dll?
- java - Jackson JSON 日期反序列化为时间戳
- node.js - 在 npm 脚本中导出 .env 文件
- html - 有什么方法可以在 scss 的帮助下更改主题
- javascript - 通过Javascript更改Flask模板中的图像
- ruby-on-rails - 在 yaml 文件中设置多个值,为什么只用 Rails 得到第一个?
- javascript - 基于输入值的表格计算器
- grafana - 如何超时 grafana 会话 cookie