Steffen
Steffen

Reputation: 733

Serving static file with Go gives an 404 error

Task:

I try to serve a static file with Golang.

Problem:

The directory content is shown, but the file in the directory is not found.

Project structure:

projectdir/

  |- main.go
  |- static/
    |- main.css
  |- templates
    |- index.tmpl 

Source snippets:

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,
}

Problem description

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.

Question

What do I miss?

Thanks in advance!

Upvotes: 2

Views: 1925

Answers (1)

user142162
user142162

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

Related Questions