render

package
v0.0.0-...-fa3d426 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 16, 2016 License: MIT, MIT Imports: 10 Imported by: 0

README

Render GoDoc

Render is a package that provides functionality for easily rendering JSON, XML, and HTML templates. This package is based on the Martini render work.

Usage

Render can be used with pretty much any web framework providing you can access the http.ResponseWriter variable from your handler. The rendering functions simply wrap Go's existing functionality for marshaling and rendering the given data.

  • HTML: Uses the html/template package to render HTML templates.
  • JSON: Uses the encoding/json package to marshal data into a JSON-encoded response.
  • XML: Uses the encoding/xml package to marshal data into an XML-encoded response.
  • Binary Data: Passes the incoming data straight through to the http.ResponseWriter.
// main.go
package main

import (
    "encoding/xml"
    "net/http"

    "gopkg.in/unrolled/render.v1"
)

type ExampleXml struct {
    XMLName xml.Name `xml:"example"`
    One     string   `xml:"one,attr"`
    Two     string   `xml:"two,attr"`
}

func main() {
    r := render.New(render.Options{})
    mux := http.NewServeMux()

    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("Welcome, visit sub pages now."))
    })

    mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
        r.Data(w, http.StatusOK, []byte("Some binary data here."))
    })

    mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"hello": "json"})
    })

    mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {
        r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"})
    })

    mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
        // Assumes you have a template in ./templates called "example.tmpl"
        // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl
        r.HTML(w, http.StatusOK, "example", nil)
    })

    http.ListenAndServe("0.0.0.0:3000", mux)
}
<!-- templates/example.tmpl -->
<h1>Hello {{.}}.</h1>
Available Options

Render comes with a variety of configuration options (Note: these are not the default option values. See the defaults below.):

// ...
r := render.New(render.Options{
    Directory: "templates", // Specify what path to load the templates from.
    Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template.
    Extensions: []string{".tmpl", ".html"}, // Specify extensions to load for templates.
    Funcs: []template.FuncMap{AppHelpers}, // Specify helper function maps for templates to access.
    Delims: render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings.
    Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8".
    IndentJSON: true, // Output human readable JSON.
    IndentXML: true, // Output human readable XML.
    PrefixJSON: []byte(")]}',\n"), // Prefixes JSON responses with the given bytes.
    PrefixXML: []byte("<?xml version='1.0' encoding='UTF-8'?>"), // Prefixes XML responses with the given bytes.
    HTMLContentType: "application/xhtml+xml", // Output XHTML content type instead of default "text/html".
    IsDevelopment: true, // Render will now recompile the templates on every HTML response.
})
// ...
Default Options

These are the preset options for Render:

    Directory: "templates",
    Layout: "",
    Extensions: []string{".tmpl"},
    Funcs: []template.FuncMap{},
    Delims: render.Delims{"{{", "}}"},
    Charset: "UTF-8",
    IndentJSON: false,
    IndentXML: false,
    PrefixJSON: []byte(""),
    PrefixXML: []byte(""),
    HTMLContentType: "text/html",
    IsDevelopment: false,
Loading Templates

By default Render will attempt to load templates with a '.tmpl' extension from the "templates" directory. Templates are found by traversing the templates directory and are named by path and basename. For instance, the following directory structure:

templates/
  |
  |__ admin/
  |      |
  |      |__ index.tmpl
  |      |
  |      |__ edit.tmpl
  |
  |__ home.tmpl

Will provide the following templates:

admin/index
admin/edit
home
Layouts

Render provides a yield function for layouts to access:

// ...
r := render.New(render.Options{
    Layout: "layout",
})
// ...
<!-- templates/layout.tmpl -->
<html>
  <head>
    <title>My Layout</title>
  </head>
  <body>
    <!-- Render the current template here -->
    {{ yield }}
  </body>
</html>

current can also be called to get the current template being rendered.

<!-- templates/layout.tmpl -->
<html>
  <head>
    <title>My Layout</title>
  </head>
  <body>
    This is the {{ current }} page.
  </body>
</html>
Character Encodings

Render will automatically set the proper Content-Type header based on which function you call. See below for an example of what the default settings would output (note that UTF-8 is the default, and binary data does not output the charset):

// main.go
package main

import (
    "encoding/xml"
    "net/http"

    "gopkg.in/unrolled/render.v1"
)

type ExampleXml struct {
    XMLName xml.Name `xml:"example"`
    One     string   `xml:"one,attr"`
    Two     string   `xml:"two,attr"`
}

func main() {
    r := render.New(render.Options{})
    mux := http.NewServeMux()

    // This will set the Content-Type header to "application/octet-stream".
    // Note that this does not receive a charset value.
    mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
        r.Data(w, http.StatusOK, []byte("Some binary data here."))
    })

    // This will set the Content-Type header to "application/json; charset=UTF-8".
    mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"hello": "json"})
    })

    // This will set the Content-Type header to "text/xml; charset=UTF-8".
    mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {
        r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"})
    })

    // This will set the Content-Type header to "text/html; charset=UTF-8".
    mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
        // Assumes you have a template in ./templates called "example.tmpl"
        // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl
        r.HTML(w, http.StatusOK, "example", nil)
    })

    http.ListenAndServe("0.0.0.0:3000", mux)
}

In order to change the charset, you can set the Charset within the render.Options to your encoding value:

// main.go
package main

import (
    "encoding/xml"
    "net/http"

    "gopkg.in/unrolled/render.v1"
)

type ExampleXml struct {
    XMLName xml.Name `xml:"example"`
    One     string   `xml:"one,attr"`
    Two     string   `xml:"two,attr"`
}

func main() {
    r := render.New(render.Options{
        Charset: "ISO-8859-1",
    })
    mux := http.NewServeMux()

    // This will set the Content-Type header to "application/octet-stream".
    // Note that this does not receive a charset value.
    mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
        r.Data(w, http.StatusOK, []byte("Some binary data here."))
    })

    // This will set the Content-Type header to "application/json; charset=ISO-8859-1".
    mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"hello": "json"})
    })

    // This will set the Content-Type header to "text/xml; charset=ISO-8859-1".
    mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {
        r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"})
    })

    // This will set the Content-Type header to "text/html; charset=ISO-8859-1".
    mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
        // Assumes you have a template in ./templates called "example.tmpl"
        // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl
        r.HTML(w, http.StatusOK, "example", nil)
    })

    http.ListenAndServe("0.0.0.0:3000", mux)
}

Integration Examples

Gin
// main.go
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "gopkg.in/unrolled/render.v1"
)

func main() {
    r := render.New(render.Options{
        IndentJSON: true,
    })

    masterGin := gin.Default()

    masterGin.GET("/", func(c *gin.Context) {
        r.JSON(c.Writer, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"})
    })

    masterGin.Run(":3000")
}
Goji
// main.go
package main

import (
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
    "gopkg.in/unrolled/render.v1"
)

func main() {
    r := render.New(render.Options{
        IndentJSON: true,
    })

    goji.Get("/", func(c web.C, w http.ResponseWriter, req *http.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"})
    })
    goji.Serve()  // Defaults to ":8000".
}
Negroni
// main.go
package main

import (
    "net/http"

    "github.com/codegangsta/negroni"
    "gopkg.in/unrolled/render.v1"
)

func main() {
    r := render.New(render.Options{
        IndentJSON: true,
    })
    mux := http.NewServeMux()

    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"})
    })

    n := negroni.Classic()
    n.UseHandler(mux)
    n.Run(":3000")
}
Traffic
// main.go
package main

import (
    "net/http"

    "github.com/pilu/traffic"
    "gopkg.in/unrolled/render.v1"
)

func main() {
    r := render.New(render.Options{
        IndentJSON: true,
    })

    router := traffic.New()
    router.Get("/", func(w traffic.ResponseWriter, req *traffic.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"})
    })

    router.Run()
}
Web.go
// main.go
package main

import (
    "net/http"

    "github.com/hoisie/web"
    "gopkg.in/unrolled/render.v1"
)

func main() {
    r := render.New(render.Options{
        IndentJSON: true,
    })

    web.Get("/(.*)", func(ctx *web.Context, val string) {
        r.JSON(ctx, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"})
    })

    web.Run("0.0.0.0:3000")
}

Documentation

Overview

Package render is a package that provides functionality for easily rendering JSON, XML, and HTML templates.

package main

import (
    "encoding/xml"
    "net/http"

    "gopkg.in/unrolled/render.v1"
)

type ExampleXml struct {
    XMLName xml.Name `xml:"example"`
    One     string   `xml:"one,attr"`
    Two     string   `xml:"two,attr"`
}

func main() {
    r := render.New(render.Options{})
    mux := http.NewServeMux()

    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("Welcome, visit sub pages now."))
    })

    mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
        r.Data(w, http.StatusOK, []byte("Some binary data here."))
    })

    mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
        r.JSON(w, http.StatusOK, map[string]string{"hello": "json"})
    })

    mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {
        r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"})
    })

    mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
        // Assumes you have a template in ./templates called "example.tmpl"
        // $ mkdir -p templates && echo "<h1>Hello HTML world.</h1>" > templates/example.tmpl
        r.HTML(w, http.StatusOK, "example", nil)
    })

    http.ListenAndServe("0.0.0.0:3000", mux)
}

Index

Constants

View Source
const (
	// ContentType header constant.
	ContentType = "Content-Type"
	// ContentLength header constant.
	ContentLength = "Content-Length"
	// ContentBinary header value for binary data.
	ContentBinary = "application/octet-stream"
	// ContentJSON header value for JSON data.
	ContentJSON = "application/json"
	// ContentHTML header value for HTML data.
	ContentHTML = "text/html"
	// ContentXHTML header value for XHTML data.
	ContentXHTML = "application/xhtml+xml"
	// ContentXML header value for XML data.
	ContentXML = "text/xml"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Data

type Data struct {
	Head
}

Data built-in renderer.

func (Data) Render

func (d Data) Render(w http.ResponseWriter, v interface{}) error

Render a data response.

type Delims

type Delims struct {
	// Left delimiter, defaults to {{.
	Left string
	// Right delimiter, defaults to }}.
	Right string
}

Delims represents a set of Left and Right delimiters for HTML template rendering.

type Engine

type Engine interface {
	Render(http.ResponseWriter, interface{}) error
}

Engine is the generic interface for all responses.

type HTML

type HTML struct {
	Head
	Name      string
	Templates *template.Template
}

HTML built-in renderer.

func (HTML) Render

func (h HTML) Render(w http.ResponseWriter, binding interface{}) error

Render a HTML response.

type HTMLOptions

type HTMLOptions struct {
	// Layout template name. Overrides Options.Layout.
	Layout string
}

HTMLOptions is a struct for overriding some rendering Options for specific HTML call.

type Head struct {
	ContentType string
	Status      int
}

Head defines the basic ContentType and Status fields.

func (Head) Write

func (h Head) Write(w http.ResponseWriter)

Write outputs the header content.

type JSON

type JSON struct {
	Head
	Indent bool
	Prefix []byte
}

JSON built-in renderer.

func (JSON) Render

func (j JSON) Render(w http.ResponseWriter, v interface{}) error

Render a JSON response.

type Options

type Options struct {
	// Directory to load templates. Default is "templates".
	Directory string
	// Layout template name. Will not render a layout if blank (""). Defaults to blank ("").
	Layout string
	// Extensions to parse template files from. Defaults to [".tmpl"].
	Extensions []string
	// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
	Funcs []template.FuncMap
	// Delims sets the action delimiters to the specified strings in the Delims struct.
	Delims Delims
	// Appends the given character set to the Content-Type header. Default is "UTF-8".
	Charset string
	// Outputs human readable JSON.
	IndentJSON bool
	// Outputs human readable XML.
	IndentXML bool
	// Prefixes the JSON output with the given bytes.
	PrefixJSON []byte
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string
	// If IsDevelopment is set to true, this will recompile the templates on every request. Default if false.
	IsDevelopment bool
}

Options is a struct for specifying configuration options for the render.Render object.

type Render

type Render struct {
	// contains filtered or unexported fields
}

Render is a service that provides functions for easily writing JSON, XML, Binary Data, and HTML templates out to a http Response.

func New

func New(options Options) *Render

New constructs a new Render instance with the supplied options.

func (*Render) Data

func (r *Render) Data(w http.ResponseWriter, status int, v []byte)

Data writes out the raw bytes as binary data.

func (*Render) HTML

func (r *Render) HTML(w http.ResponseWriter, status int, name string, binding interface{}, htmlOpt ...HTMLOptions)

HTML builds up the response from the specified template and bindings.

func (*Render) JSON

func (r *Render) JSON(w http.ResponseWriter, status int, v interface{})

JSON marshals the given interface object and writes the JSON response.

func (*Render) Render

func (r *Render) Render(w http.ResponseWriter, e Engine, data interface{})

Render is the generic function called by XML, JSON, Data, HTML, and can be called by custom implementations.

func (*Render) XML

func (r *Render) XML(w http.ResponseWriter, status int, v interface{})

XML marshals the given interface object and writes the XML response.

type XML

type XML struct {
	Head
	Indent bool
	Prefix []byte
}

XML built-in renderer.

func (XML) Render

func (x XML) Render(w http.ResponseWriter, v interface{}) error

Render an XML response.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL