Routing in Go
From time to time I build some server things in Go. The standard library already comes with a lot of functionality, but sometimes lacks essential features. One of them is a flexible router with parameters.
Don’t get me wrong – you can handle routing with the standard library, but it’s way more comfortable to handle more complex routing with a third party library. I chose mux from the Gorilla web toolkit. It comes with various modules but they are indeed modular. Just need the router but no sockets? Just use the router then!
The usage is pretty self explaining. The hardest part was to figure out how to handle or throw 404 errors.
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/", RootHandler)
router.HandleFunc("/hello/{name}/", HelloHandler)
router.NotFoundHandler = http.HandlerFunc(NotFoundHandler)
http.Handle("/", router)
http.ListenAndServe(":3000", nil)
}
func RootHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("This is a webserver. Check /hello/yourname/"))
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.Write([]byte("Hello, " + vars["name"]))
}
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
w.Write([]byte("404 – Not found!"))
}
For more tips on HTTP responses, check these handy Golang Response Snippets.