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.