Skip to content

Instantly share code, notes, and snippets.

@flowchartsman
Created February 17, 2019 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flowchartsman/88423b0201a1d85e0f4ccf872ce0b6f0 to your computer and use it in GitHub Desktop.
Save flowchartsman/88423b0201a1d85e0f4ccf872ce0b6f0 to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"github.com/gorilla/mux"
)
// example of a basic handler
func fooHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("foo route\n"))
}
// example of a handler using vars
func barHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("bar route got " + mux.Vars(r)["barID"] + "\n"))
}
// Dedicated handler to serve index.html to root route
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
}
func main() {
r := mux.NewRouter()
// these two are pretty standard
r.HandleFunc("/foo", fooHandler).Methods("GET")
r.HandleFunc("/bar/{barID}", barHandler).Methods("GET")
// stripPrefix just removes the "static" prefix and passes what's left to http.FileServer. However, there is a special case for the
// user requesting "index.htm[l]" where it will redirect to the root. See: https://golang.org/src/net/http/fs.go#L540
// BUT, since http.StripPrefix has removed the static prefix, the redirect points back to root. But, our next route below serves
// index.html statically from root. Since browsers follow permanent redirects automatically, this is transparent from a browser
// perspective, but requires `curl -L` to properly follow with curl.
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
r.HandleFunc("/", rootHandler).Methods("GET")
http.ListenAndServe(":8080", r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment