Why ServeFile function in http package redirect when matching "/index.html" ?

632 views
Skip to first unread message

ASSISS

unread,
Nov 24, 2009, 5:34:48 AM11/24/09
to golang-nuts
I am writting a simple test using http package. I use http.ServeFile
to handle static html files.
I got a strange question when the url match "index.html".

For example:

I have this httpserv running with a subdir "static" (which has a lot
html files).

func StaticFileServer(c *http.Conn, req *http.Request) {
http.ServeFile(c, req, "static"+req.URL.Path);
}
...
...
in main:
http.Handle("/", http.HandlerFunc(StaticFileServer));

when I request http://localhost/, the server returned static/
index.html. It's ok.

when I request http://localhost/index.html, the server just redirect
to http://localhost/static/ -- it's not what I want.

Why doing so ?
I checked src/pkg/http/fs.go, and found that in func
serveFileInternal, it would always redirect the url ending with "/
index.html".

Is this redirect necessary ? I think it's not, or someone please
fixme.

my version `hg log -l 1`:
4199:67d92d7e6694

Russ Cox

unread,
Nov 24, 2009, 2:48:36 PM11/24/09
to ASSISS, golang-nuts
> I have this httpserv running with a subdir "static" (which has a lot
> html files).
>
> func StaticFileServer(c *http.Conn, req *http.Request) {
>        http.ServeFile(c, req, "static"+req.URL.Path);
> }
> ...
> ...
> in main:
>    http.Handle("/", http.HandlerFunc(StaticFileServer));
>
> when I request http://localhost/, the server returned static/
> index.html. It's ok.
>
> when I request http://localhost/index.html, the server just redirect
> to http://localhost/static/ -- it's not what I want.
>
> Why doing so ?

It's good form to redirect requests to the canonical URL,
the file server assumes that any path ending in /index.html
should be rewritten to drop the "index.html", e.g.
http://golang.org/ not http://golang.org/index.html.

What you've found is just a bug - it should be redirecting
to http://localhost/ not http://localhost/static/.

Fixed in the current tree, will be in the next release.
As usual, hg pull -u to get the fix early.

Russ
Reply all
Reply to author
Forward
0 new messages