At https://www.alexedwards.net/blog/serving-static-sites-with-go, there's an example of a static file server serving sites in a single directory: static
.
File: app.go
...
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
log.Println("Listening...")
http.ListenAndServe(":3000", nil)
}
However, I've found that I can get the same results with the following.
func main() {
fs := http.FileServer(http.Dir(".")) // root at the root directory.
http.Handle("/static/", fs) //leave off the StripPrefix call.
log.Println("Listening...")
http.ListenAndServe(":3000", nil)
}
Are there any (performanace or security) downsides to doing it this way? I can see that I'd have to use StripPrefix
if my location of the files on the filesystem did not match the URL they were served at, but in this case it seems as though the call to StripPrefix
is unnecessary.
Edit: I forgot to mention, but I've had a look into this myself. Performance-wise, it doesn't seem to be a problem, since the call to FileServer
doesn't actually load the files into memory; it just stores away the address. Security-wise, this seems to be exactly the same: I attempted a directory-traversal attack using something like the following.
$ curl -i --path-as-is 'http://localhost:3000/static/../sensitive.txt'
but I got a 301 response with both versions, which surprised me a little bit.