I am trying to follow an online video course on golang and I am getting an error serving static html files.
package main
import (
"io/ioutil"
"net/http"
)
func main() {
http.Handle("/", new(MyHandler))
http.ListenAndServe(":8000", nil)
}
type MyHandler struct {
http.Handler
}
func (this *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
path := "public/" + req.URL.Path
data, err := ioutil.ReadFile(string(path))
if err == nil {
w.Write(data)
} else {
w.WriteHeader(404)
w.Write([]byte("404 - " + http.StatusText(404)))
}
}
My folder structure looks like this.
Based on the link to your folder structure I'm going to guess that you need path := "../public/" + req.URL.Path
. Your application is running from the bin
directory so you can't go directly into a sibling directory, you need ..
to go out one directory at which point public
is actually an option.
Correct path is ../../public, because your main.go file is in main/src folder.