http.FileServer修改Header

定义一个函数包裹Handler,返回HandleFunc,然后通过ResponseWriter修改Header。

func changeHeaderThenServe(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Set some header.
        w.Header().Add("Keep-Alive", "300")
        // Serve with the actual handler.
        h.ServeHTTP(w, r)
    }
}

通过FilServer访问静态资源。

func main() {
  h := http.FileServer(http.Dir("static/"))
  h = http.StripPrefix("/static/", h)
  http.HandleFunc("/static/", changeHeaderThenServe(h))
  http.ListenAndServe("localhost:80", nil)
}

参考: Google Groups

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容