Go to: HTTP static directories are not served

I do not understand why my static resources are not 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, going to http: //myhost.fake/css/ or http: //myhost.fake/css/main.css (they exist on the file system), I get error 404. The same is true if I will replace "./css" with the full directory path. Also for js static directory. My other handlers are working fine. I am on Linux. Thanks!

+6
source share
2 answers

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

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

This should do it:

 http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css")))) 
+12
source

I can’t check 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,...} are received correctly. The same story about scripts.

0
source

All Articles