Stucked with loading public content in my webapp

My webapp folders structure is:

appname/public/html/home.html
appname/src/github.com/appname/webapp/main.go

Where the appname is a folder inside a src folder of $GOPATH

I’m trying to load a file in browser from public folder this way:

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		f, err := os.Open("public" + r.URL.Path)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			log.Println(err)
		}
		defer f.Close()
		io.Copy(w, f)
	})
	http.ListenAndServe(":8080", nil)
}

I compile the app like go run main.go and there are no erros in console. Then I open it in browser like:

http://localhost:8080/html/home.html

And I get in console:

2019/03/17 16:18:37 open /public/html/home.html: The system cannot find the path specified.

And in browser: HTTP ERROR 500

What am I doing wrong?

You have to have a handler for serving the HTML file also. The good thing is that go already include one in the http package. See: https://golang.org/pkg/net/http/#FileServer

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.