Reputation: 45
I need to serve an html file to localhost:8080/lvlione
but the FileServer
function in golang doesn't seem to work.
Here is main.go:
package main
import (
"log" //logging that the server is running and other stuff
"net/http" //serving files and stuff
)
func main() {
//servemux
server := http.NewServeMux()
//handlers that serve the home html file when called
fs := http.FileServer(http.Dir("./home"))
os := http.FileServer(http.Dir("./lvlone")) //!!this is what is broken!!
//handles paths by serving correct files
//there will be if statements down here that check if someone has won or not soon
server.Handle("/", fs)
server.Handle("/lvlione", os)
//logs that server is Listening
log.Println("Listening...")
//starts server
http.ListenAndServe(":8080", server)
}
There is a folder in this directory called lvlone with one file in it (index.html). When I point my browser to localhost:8080/lvlione
it returns 404
, but when it is pointed to localhost:8080
it returns the correct file.
Upvotes: 1
Views: 2413
Reputation: 10000
You need to call http.StripPrefix
to remove the extra lvlone
from the directory path.
server.Handle("/lvlone/", http.StripPrefix("/lvlone/", os))
By default the http.FileServer
assumes the path given to it is the root path, and appends the URL to it. If it is to serve a subdirectory of the virtual path, then that needs to be stripped from the path.
And note that you need to have the trailing slashes in both places.
Upvotes: 2