Using the render package

If you want rendering JSON and HTML to be even simpler, there is the
github.com/unrolled/render package. This package was inspired by the
martini-contrib/render package and is my goto when it comes to rendering data
for presentation in my web applications.

  1. package main
  2. import (
  3. "net/http"
  4. "gopkg.in/unrolled/render.v1"
  5. )
  6. func main() {
  7. r := render.New(render.Options{})
  8. mux := http.NewServeMux()
  9. mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  10. w.Write([]byte("Welcome, visit sub pages now."))
  11. })
  12. mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
  13. r.Data(w, http.StatusOK, []byte("Some binary data here."))
  14. })
  15. mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
  16. r.JSON(w, http.StatusOK, map[string]string{"hello": "json"})
  17. })
  18. mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
  19. // Assumes you have a template in ./templates called "example.tmpl"
  20. // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl
  21. r.HTML(w, http.StatusOK, "example", nil)
  22. })
  23. http.ListenAndServe(":8080", mux)
  24. }

Exercises

  1. Have fun playing with all of the options available when calling render.New()
  2. Try using the .yield helper function (with the curly braces) and a layout with HTML templates.