1

I'm trying to set up an HTTP server in Go using only the standard library. The server should be able to accept requests of the form /:uuid and should be able to serve an index.html file as well as a css file imported in it. This is what my code looked like:

 func indexHandler(w http.ResponseWriter, r *http.Request) {
    // serve index.html
    if r.URL.Path == "/" {
        http.ServeFile(w, r, "./web/index.html")
    } else {
        // if the path is /randomwords, redirect to mapped URL
        randomwords := r.URL.Path[1:]
        url := getMappedURL(randomwords)
        http.Redirect(w, r, url, http.StatusFound)
    }
}

func main() {
  http.HandleFunc("/", indexHandler)
  log.Println("listening on port 5000")
  http.ListenAndServe(":5000", nil)
}

This serves the html file and is able to accept requests like /:something but the problem is that it doesn't include the CSS file. After some googling, I changed the main function to this:

func main() {
    fs := http.FileServer(http.Dir("web"))
    http.Handle("/", fs)
    log.Println("listening on port 5000")
    http.ListenAndServe(":5000", nil)
}

This serves both the HTML and the CSS files but it doesn't allow routes of the form :something. I can't figure out how to have both of these features.

1 Answer 1

2

Your original solution was nearly there, all you have to do is add a branch:

if r.URL.Path == "/" {
    http.ServeFile(w, r, "./web/index.html")
} else if r.URL.Path == "/styles.css" {
    http.ServeFile(w, r, "./web/styles.css")
} else {
    // ...

Of course this can be tailored as needed - you could check for any file ending in ".css" using strings.HasSuffix, for example.

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

6 Comments

Hmm.. this seems a bit hard-coded I think. Is there any way to serve all CSS files in a generic way similar to this? or serve all files in web?
There are a lot of ways you could do it. The question said you wanted to serve "a css file", but the basic technique of "look at the URL and determine what to serve" that you're already using for index.html offers plenty of flexibility to do absolutely anything.
What do you mean "nothing"? What would you recommend to make this more general?
I'm not sure I follow, I never said "nothing". To make this more general, you'll have to figure out what you need and implement it. You can't have two handlers that both handle every URL; you'll need to write some logic to decide which handler serves what.
Sorry I mean "anything".
|

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.