I've a simple folder :
Test/
main.go
Images/
image1.png
image2.png
index.html
In main main.go I just put :
package main
import (
"net/http"
)
func main(){
fs := http.FileServer(http.Dir("./Images"))
http.Handle("/Images/*", fs)
http.ListenAndServe(":3003", nil)
}
But when I curl on http://localhost:3003/Images/ or even I add to path file's name, it doesn't work. I don't understand because it's the same as the reply given on this subject
Can you tell me so that this does not work ?
You need to remove *
and add extra sub-folder Images
:
This works fine:
Test/
main.go
Images/
Images/
image1.png
image2.png
index.html
Code:
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./Images"))
http.Handle("/Images/", fs)
http.ListenAndServe(":3003", nil)
}
Then go run main.go
And:
Or simply use:
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./Images"))
http.Handle("/", fs)
http.ListenAndServe(":3003", nil)
}
with: http://localhost:3003/
Dot in ./Images refer cwd current working directory, not you project root. For your server to work you must run it from Test/ directory, or address Images with absolute rooted path.
The reason the request failed to return what you expected is because they did not match the pattern defined in the http.Handle(pattern string, handler Handler)
call. The ServeMux documentation provides a description of how to compose patterns. Any request is prefixed matched from most specific to least specific. It appears as though you have assumed a glob pattern can be used. Your handler would have been invoked with requests to /Images/*<file system path>
. You need to define a directory path like so, Images/
.
On a side note, it is worth considering how your program gets the directory path to serve files from. Hard coding a relative means your program will only function within a specific location within the filesystem which incredibly brittle. You could use a command line argument to allow users to specify a path or use a configuration file parsed at runtime. These considerations make your program easy to modularize and test.