Go server not serving files properly

I am creating a SPA. I am trying to respond all requests with index.html (I handle routing on the frontend).

My directory structure look like this:

Backend

-- main.go

Frontend

..(some other files)..

-- index.html

Whole project is located in "C:\Go\Projects\src\github.com\congrady\Bakalarka"

My main.go file looks like this:

package main

import (
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "../Frontend/index.html")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

When I run my main.go file (using go run), my localhost always responds with "404 page not found". When I try to serve static content using fmt, everything works fine.

Please help, I'm stuck on this for a really long time and I can't get it to work. Thanks

Upvotes: 1

Views: 939

Answers (1)

tike
tike

Reputation: 2294

Be aware that if you hardcode relative paths in your source file, the directory which you are in when starting the app matters.

In the current configuration, make sure to start the app from the Backend directory, i.e.

C:\Go\Projects\src\github.com\congrady\Bakalarka\Backend,

NOT your apps root directory

C:\Go\Projects\src\github.com\congrady\Bakalarka

or

change the string in the main file to Frontend/index.html and run from

C:\Go\Projects\src\github.com\congrady\Bakalarka

Upvotes: 0

Related Questions