ChunkCoder
ChunkCoder

Reputation: 307

Go set header for all handlers

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?

Upvotes: 1

Views: 634

Answers (1)

Thundercat
Thundercat

Reputation: 120941

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.

Upvotes: 3

Related Questions