Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 304
Jeremy Avatar asked Mar 19 '13 19:03

Jeremy


1 Answers

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"))))
like image 69
lukad Avatar answered Sep 20 '22 21:09

lukad