2

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!

1 Answer 1

4

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"))))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.