1

I need to serve an html file to localhost:8080/lvlione but the FileServer function in golang doesn't seem to work.

Here is main.go:

package main

import (
    "log"      //logging that the server is running and other stuff
    "net/http" //serving files and stuff
)

func main() {
    //servemux
    server := http.NewServeMux()

    //handlers that serve the home html file when called
    fs := http.FileServer(http.Dir("./home"))
    os := http.FileServer(http.Dir("./lvlone")) //!!this is what is broken!!

    //handles paths by serving correct files
    //there will be if statements down here that check if someone has won or not soon
    server.Handle("/", fs)
    server.Handle("/lvlione", os)

    //logs that server is Listening
    log.Println("Listening...")
    //starts server
    http.ListenAndServe(":8080", server)
}

There is a folder in this directory called lvlone with one file in it (index.html). When I point my browser to localhost:8080/lvlione it returns 404, but when it is pointed to localhost:8080 it returns the correct file.

1 Answer 1

2

You need to call http.StripPrefix to remove the extra lvlone from the directory path.

      server.Handle("/lvlone/", http.StripPrefix("/lvlone/", os))

By default the http.FileServer assumes the path given to it is the root path, and appends the URL to it. If it is to serve a subdirectory of the virtual path, then that needs to be stripped from the path.

And note that you need to have the trailing slashes in both places.

Sign up to request clarification or add additional context in comments.

2 Comments

would I replace the handler I currently have for the /lvlione path or do I need to change more than that? (thanks for the help)
@PersonPerson You should be able to make only the change specified. If any other change was necessary, I should have mentioned it.

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.