| 1 | /*Package render is a package that provides functionality for easily rendering JSON, XML, binary data, and HTML templates. |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "encoding/xml" |
| 7 | "net/http" |
| 8 | |
| 9 | "github.com/unrolled/render" |
| 10 | ) |
| 11 | |
| 12 | type ExampleXml struct { |
| 13 | XMLName xml.Name `xml:"example"` |
| 14 | One string `xml:"one,attr"` |
| 15 | Two string `xml:"two,attr"` |
| 16 | } |
| 17 | |
| 18 | func main() { |
| 19 | r := render.New() |
| 20 | mux := http.NewServeMux() |
| 21 | |
| 22 | mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { |
| 23 | w.Write([]byte("Welcome, visit sub pages now.")) |
| 24 | }) |
| 25 | |
| 26 | mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) { |
| 27 | r.Data(w, http.StatusOK, []byte("Some binary data here.")) |
| 28 | }) |
| 29 | |
| 30 | mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) { |
| 31 | r.Text(w, http.StatusOK, "Plain text here") |
| 32 | }) |
| 33 | |
| 34 | mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) { |
| 35 | r.JSON(w, http.StatusOK, map[string]string{"hello": "json"}) |
| 36 | }) |
| 37 | |
| 38 | mux.HandleFunc("/jsonp", func(w http.ResponseWriter, req *http.Request) { |
| 39 | r.JSONP(w, http.StatusOK, "callbackName", map[string]string{"hello": "jsonp"}) |
| 40 | }) |
| 41 | |
| 42 | mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) { |
| 43 | r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"}) |
| 44 | }) |
| 45 | |
| 46 | mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) { |
| 47 | // Assumes you have a template in ./templates called "example.tmpl". |
| 48 | // $ mkdir -p templates && echo "<h1>Hello HTML world.</h1>" > templates/example.tmpl |
| 49 | r.HTML(w, http.StatusOK, "example", nil) |
| 50 | }) |
| 51 | |
| 52 | http.ListenAndServe("127.0.0.1:3000", mux) |
| 53 | } |
| 54 | */ |
| 55 | package render |