Search code examples
httpgohttp-status-code-404handler

Golang net/http fileserver giving 404 on any pattern other than "/"


Hello awesome stackoverflow community,

Apologies for the lame question. I've been playing around with the net/http package in Go, and was trying to set an http.Handle to serve the contents of a directory. My code to the Handle is

 func main() {
     http.Handle("/pwd", http.FileServer(http.Dir(".")))
     http.HandleFunc("/dog", dogpic)
     err := http.ListenAndServe(":8080", nil)
     if err != nil {
         panic(err)
     }
 } 

My dogpic handler is using os.Open and an http.ServeContent, which is working fine.

However, when I try to browse localhost:8080/pwd I am getting a 404 page not found, but when I change the pattern to route to /, as

http.Handle("/", http.FileServer(http.Dir(".")))

it is showing the contents of the current page. Can someone please help me figure out why the fileserver is not working with other patterns but only /?

Thank you.


Solution

  • The http.FileServer as called with your /pwd handler will take a request for /pwdmyfile and will use the URI path to build the filename. This means that it will look for pwdmyfile in the local directory.

    I suspect you only want pwd as a prefix on the URI, not in the filenames themselves.

    There's an example for how to do this in the http.FileServer doc:

    // To serve a directory on disk (/tmp) under an alternate URL
    // path (/tmpfiles/), use StripPrefix to modify the request
    // URL's path before the FileServer sees it:
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    

    You'll want to do something similar:

    http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("."))))