7

I don't understand why my static resources aren't being served. Here is the code:

func main() {
    http.HandleFunc("/", get_shows)
    http.HandleFunc("/get",  get_show_json)
    http.HandleFunc("/set", set_shows)
    http.Handle("/css/", http.FileServer(http.Dir("./css")))
    http.Handle("/js/", http.FileServer(http.Dir("./js")))
    http.ListenAndServe(":8080", nil)
}

When I run the program, navigating to http://myhost.fake/css/ or to http://myhost.fake/css/main.css (these exists in the filesystem), I get a 404 error. The same is true if I replace "./css" with the full path to the directory. Ditto for the js static directory. My other handlers work fine. I am on a linux. Thanks!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Jeremy
  • 93
  • 6
  • Why is this filed under "linux"? How can I make "Go" the main category of the question? – Jeremy Mar 19 '13 at 19:10
  • 2
    I think perhaps right now it's looking for `/full/path/to/css/css/`. Try giving the `http.Dir()` the parent directory of the `js` and `css` directories. – the system Mar 19 '13 at 19:15
  • 3
    @thesystem, you're right. This isn't obvious to me from the documentation at all, though. – Jeremy Mar 19 '13 at 19:22
  • @Jeremy - this is why the answer including `http.StripPrefix` is correct. And I agree -- it's not obvious in the docs. – Dan Esparza Oct 21 '14 at 18:07

2 Answers2

13

Your handler path (/css/) is passed to the FileServer handler plus the file after the prefix. That means when you visit http://myhost.fake/css/test.css your FileServer is trying to find the file ./css/css/test.css.

The http package provides the function StripPrefix to strip the /css/ prefix.

This should do it:

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
lukad
  • 17,287
  • 3
  • 36
  • 53
  • 1
    Thanks. I'm now using `http.Handle("/css/", http.FileServer(http.Dir(".")))` which is working as expected. – Jeremy Mar 19 '13 at 19:29
  • 2
    Also, bear in mind that a relative path is resolved with respect to the directory from which your server static executable is run (not relative to that binary). To debug a problem, I've found it useful to toss `log.Printf(os.Getwd())` in there or list the files. – dgh Aug 04 '15 at 05:50
0

I cannot verify it now, but IIRC: s/"./css"/"css"/; s/"./js"/"js"/.

EDIT: Now that I can finally check the sources: This is what I did and what works for me:

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

All images in ./images/*.{gif,png,...} get served properly. The same story about scripts.

zzzz
  • 87,403
  • 16
  • 175
  • 139