2

What's wrong with http.Handle("/static/", http.FileServer(http.Dir("")))?

The shortest example I can find looks like this:

fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

Is http.StripPrefix necessary?

twharmon
  • 4,153
  • 5
  • 22
  • 48
  • 1
    Take a look at [Why do I need to use http.StripPrefix to access my static files?](https://stackoverflow.com/questions/27945310/why-do-i-need-to-use-http-stripprefix-to-access-my-static-files) – putu Jun 03 '17 at 10:35

1 Answers1

4

No it is not required, but if you DO NOT use it the path used to find the file will include the prefix. This is clearer with an example, so imagine your folder structure was:

main.go
static/
  styles.css

And you serve the files with:

http.Handle("/static/", http.FileServer(http.Dir("")))

Then a user requesting the file at yoursite.com/static/styles.css would get the styles.css file in the static dir. But for this to work your paths must line up perfectly.

Most people prefer to do the following instead:

fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

Because they could change their URL path to be something like /assets/ without needing to rename the static dir (or vise versa - change the local dir structure w/out updating the URL path).

TL;DR - Path prefix isn't required but is useful to break any requirements of URL paths and local directory structure matching perfectly.

joncalhoun
  • 1,498
  • 1
  • 17
  • 22