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!
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"))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With