http.FileServer change headers

2,599 views
Skip to first unread message

Max

unread,
Aug 15, 2013, 9:25:51 AM8/15/13
to golan...@googlegroups.com
What is correct way to change headers sent by http.FileServer ?

Thanks

Kamil Kisiel

unread,
Aug 15, 2013, 12:21:03 PM8/15/13
to golan...@googlegroups.com
I don't think you can. It uses serveContent internally which does a bunch of sniffing for content type, length, etc.

You can just write your own handler with similar API if you want it to work differently.

Thomas Bushnell, BSG

unread,
Aug 15, 2013, 12:22:47 PM8/15/13
to Kamil Kisiel, golang-nuts
If you use ServeContent, instead of FileServer, you have access to the ResponseWriter, and you can create your own which sits in between the ServeContent code and the real ResponseWriter, and that gives you complete control. But you lose the filesystem handling in FileServer.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Brad Fitzpatrick

unread,
Aug 15, 2013, 12:23:06 PM8/15/13
to Max, golang-nuts
Just set headers in your ServerHTTP before or after you call its ServeHTTP(rw, r)

On Thu, Aug 15, 2013 at 6:25 AM, Max <max.se...@gmail.com> wrote:
What is correct way to change headers sent by http.FileServer ?

Thanks

--

ace....@gmail.com

unread,
Mar 1, 2014, 12:00:50 PM3/1/14
to golan...@googlegroups.com, Max
Hello Brad, I'm new to Go and I'm facing the same issue. My assets served by FileServer aren't being cached. I don't quite follow your suggestion/answer, would you be kind enough to provide a small code snippet?

Soheil Hassas Yeganeh

unread,
Mar 1, 2014, 12:30:30 PM3/1/14
to ace....@gmail.com, golan...@googlegroups.com, Max
Probably something like this:

package main

import (
"net/http"
)

func main() {
changeHeaderThenServe := func(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)
}
}

http.Handle("/", changeHeaderThenServe(http.FileServer(http.Dir("files"))))
panic(http.ListenAndServe(":8080", nil))
}

-- Soheil

ace....@gmail.com

unread,
Mar 1, 2014, 1:33:34 PM3/1/14
to golan...@googlegroups.com, ace....@gmail.com, Max, soh...@cs.toronto.edu
Works great! Thanks a bunch Soheil!
Reply all
Reply to author
Forward
0 new messages