import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8080", nil)
}
I navigate to localhost:8080/ and get a 404 error. What am i doing wrong?
Try this:
import (
"net/http"
"os"
)
func main() {
server.RegisterHandlers()
// Get the running directory.
runningDirectory, err := os.Getwd()
if err != nil {
// Handle the error.
return err
}
http.Handle("/", http.FileServer(http.Dir(runningDirectory + "/static"))
http.ListenAndServe(":8080", nil)
}
With the following structure:
main.go
static
|- index.html
And with main.go
containing:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("static")))
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
After running your solution with go run main.go
, you should be able to go to localhost:8080/
and end up with the content of index.html
.
If it doesn't work, maybe the added error handling might help out. The code is correct.