hey
hey

Reputation: 7809

how to serve static files with http ? go

I'm using the snippet below:

fa := http.FileServer(http.Dir("attach/"))
http.Handle("/attach", fa)

The files are located into /attach/ directory. However when I hit localhost/attach or localhost/attach/anyfile it throws not found error

Upvotes: 0

Views: 121

Answers (2)

JimB
JimB

Reputation: 109318

The FileServer handler serves the directory content from root, but the handler receives the full path from the request. If you are handling at a path other than /, you need to strip that prefix off.

fa := http.FileServer(http.Dir("/attach"))
http.Handle("/attach/", http.StripPrefix("/attach/", fa))

http://golang.org/pkg/net/http/#example_FileServer_stripPrefix

Upvotes: 3

atrn
atrn

Reputation: 92

If the files are located under /attach then the pathname used with http.Dir() is wrong, unless the current directoy is /.

Upvotes: 0

Related Questions