URL Routing

For some simple applications, the default http.ServeMux can take you pretty
far. If you need more power in how you parse URL endpoints and route them to
the proper handler, you may need to pull in a third party routing framework.
For this tutorial, we will use the popular
github.com/julienschmidt/httprouter library as our router.
github.com/julienschmidt/httprouter is a great choice for a router as it is a
very simple implementation with one of the best performance benchmarks out of
all the third party Go routers.

In this example, we will create some routing for a RESTful resource called
“posts”. Below we define mechanisms to view index, show, create, update,
destroy, and edit posts.

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/julienschmidt/httprouter"
  6. )
  7. func main() {
  8. r := httprouter.New()
  9. r.GET("/", HomeHandler)
  10. // Posts collection
  11. r.GET("/posts", PostsIndexHandler)
  12. r.POST("/posts", PostsCreateHandler)
  13. // Posts singular
  14. r.GET("/posts/:id", PostShowHandler)
  15. r.PUT("/posts/:id", PostUpdateHandler)
  16. r.GET("/posts/:id/edit", PostEditHandler)
  17. fmt.Println("Starting server on :8080")
  18. http.ListenAndServe(":8080", r)
  19. }
  20. func HomeHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  21. fmt.Fprintln(rw, "Home")
  22. }
  23. func PostsIndexHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  24. fmt.Fprintln(rw, "posts index")
  25. }
  26. func PostsCreateHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  27. fmt.Fprintln(rw, "posts create")
  28. }
  29. func PostShowHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  30. id := p.ByName("id")
  31. fmt.Fprintln(rw, "showing post", id)
  32. }
  33. func PostUpdateHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  34. fmt.Fprintln(rw, "post update")
  35. }
  36. func PostDeleteHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  37. fmt.Fprintln(rw, "post delete")
  38. }
  39. func PostEditHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
  40. fmt.Fprintln(rw, "post edit")
  41. }

Exercises

  1. Explore the documentation for github.com/julienschmidt/httprouter.
  2. Find out how well github.com/julienschmidt/httprouter plays nicely with existing http.Handlers like http.FileServer
  3. httprouter has a very simple interface. Explore what kind of abstractions can be built on top of this fast router to make building things like RESTful routing easier.