2

My project structure is as follows:

/rootfolder
    index.html
    main.js
    main.go

I'm trying to serve the static javascript file through FileServer(), which always returns the index.html as a response instead of the main.js

In main.go:

serveFile := http.StripPrefix("/res/", http.FileServer(http.Dir(".")))
http.HandleFunc("/", indexHandler)
http.Handle("/res", serveFile)
http.ListenAndServe(":8080", nil)

Inside index.html main.js is referenced as follows:

<script src="/res/main.js"></script>

From the network tab in my browser, it appears that FileServer() is always returning the index.html file as a response to /res/main.js

1 Answer 1

3

Register the file handler with a trailing slash to indicate that you want to match the subtree. See the documentation for more info on the use of the trailing slash.

http.Handle("/res/", serveFile)

Also, use Handle instead of HandleFunc.

The index file was served because "/" matches all paths not matched by some other path. To return 404 in these cases, update the index handler to:

func indexHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
      http.Error(w, "Not found", 404)
      return
    }
    ... whatever code you had here before.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.