Jeremy
Jeremy

Reputation: 93

http static directories aren't being served

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!

Upvotes: 7

Views: 2124

Answers (2)

zzzz
zzzz

Reputation: 91253

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.

Upvotes: 0

lukad
lukad

Reputation: 17863

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"))))

Upvotes: 13

Related Questions