Reputation: 733
I try to serve a static file with Golang.
The directory content is shown, but the file in the directory is not found.
projectdir/
|- main.go
|- static/
|- main.css
|- templates
|- index.tmpl
main.go
func serv() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8666",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
If I start the program and point my browser to 127.0.0.1:8666/static/, the content of the directory ./static is listed, i.e. main.css
If I click the file main.css, the server response is 404.
What do I miss?
Thanks in advance!
Upvotes: 2
Views: 1925
Reputation:
The Gorilla router differs from Go's, in that Gorilla will only match the exact URL given, and not just the URL prefix. This is explained in more detail in the Gorilla documentation, where it explains how PathPrefix
can be used for serving files:
r.PathPrefix("/static/").
Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
Upvotes: 4