Methods to serve static files under a path other than the root

77 views
Skip to first unread message

Jingguo Yao

unread,
May 11, 2020, 9:33:42 AM5/11/20
to golang-nuts
The following code serves the files inside ./data directory on localhost:8080/:
 
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("./data")))) 

The following code does the same:

http.Handle("/", http.FileServer(http.Dir("./data")))
log.Fatal(http.ListenAndServe(":8080", nil))

The following code serves files inside ./data directory on localhost:8080/h. This method is suggested by https://golang.org/pkg/net/http/#FileServer.

http.Handle("/h/", http.StripPrefix("/h/", http.FileServer(http.Dir("./data"))))
log.Fatal(http.ListenAndServe(":8080", nil))

My first intuition is to use the following code to serve files on localhost:8080/h. It does not work. But no errors report. What does the following code do?

http.Handle("/h", http.FileServer(http.Dir("./data")))
log.Fatal(http.ListenAndServe(":8080", nil))

Brian Candler

unread,
May 11, 2020, 10:45:22 AM5/11/20
to golang-nuts
What your code does is when you access localhost:8080/h, it will serve the contents of the file ./data/h

If ./data/h does not exist, it will give a 404.

If ./data/h is a directory, it will redirect to /h/  - but then there's no route which matches that path, so after following the redirect you'll get a 404.

Note that "/h" only matches the path /h - if you want a subtree you need the trailing slash.

If you changed it to:

http.Handle("/h/", http.FileServer(http.Dir("./data")))
log.Fatal(http.ListenAndServe(":8080", nil))

then you'll find
curl localhost:8080/h/xxx
shows you the contents of data/h/xxx

Reply all
Reply to author
Forward
0 new messages