render

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2023 License: MIT Imports: 15 Imported by: 1,235

README

Render GoDoc Test

Render is a package that provides functionality for easily rendering JSON, XML, text, binary data, and HTML templates.

Usage

Render can be used with pretty much any web framework providing you can access the http.ResponseWriter from your handler. The rendering functions simply wraps Go's existing functionality for marshaling and rendering 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.
  • Text: Passes the incoming string straight through to the http.ResponseWriter.
// main.go
package main

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

    "github.com/unrolled/render"
)

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

func main() {
    r := render.New()
    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("/text", func(w http.ResponseWriter, req *http.Request) {
        r.Text(w, http.StatusOK, "Plain text here")
    })

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

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

    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", "World")
    })

    http.ListenAndServe("127.0.0.1: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.
    FileSystem: &LocalFileSystem{}, // Specify filesystem from where files are loaded.
    Asset: func(name string) ([]byte, error) { // Load from an Asset function instead of file.
      return []byte("template content"), nil
    },
    AssetNames: func() []string { // Return a list of asset names for the Asset function
      return []string{"filename.tmpl"}
    },
    Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template or {{ partial "css" }} to render a partial from 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 content-types. Default is "UTF-8".
    DisableCharset: true, // Prevents the charset from being appended to the content type header.
    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.
    UseMutexLock: true, // Overrides the default no lock implementation and uses the standard `sync.RWMutex` lock.
    UnEscapeHTML: true, // Replace ensure '&<>' are output correctly (JSON only).
    StreamingJSON: true, // Streams the JSON response via json.Encoder.
    HTMLTemplateOption: "missingkey=error", // Sets the option value for HTML templates. See https://pkg.go.dev/html/template#Template.Option for a list of known options.
    RequirePartials: true, // Return an error if a template is missing a partial used in a layout.
    DisableHTTPErrorRendering: true, // Disables automatic rendering of http.StatusInternalServerError when an error occurs.
})
// ...
Default Options

These are the preset options for Render:

r := render.New()

// Is the same as the default configuration options:

r := render.New(render.Options{
    Directory: "templates",
    FileSystem: &LocalFileSystem{},
    Asset: nil,
    AssetNames: nil,
    Layout: "",
    Extensions: []string{".tmpl"},
    Funcs: []template.FuncMap{},
    Delims: render.Delims{"{{", "}}"},
    Charset: "UTF-8",
    DisableCharset: false,
    IndentJSON: false,
    IndentXML: false,
    PrefixJSON: []byte(""),
    PrefixXML: []byte(""),
    BinaryContentType: "application/octet-stream",
    HTMLContentType: "text/html",
    JSONContentType: "application/json",
    JSONPContentType: "application/javascript",
    TextContentType: "text/plain",
    XMLContentType: "application/xhtml+xml",
    IsDevelopment: false,
    UseMutexLock: false,
    UnEscapeHTML: false,
    HTMLTemplateOption: "",
    StreamingJSON: false,
    RequirePartials: false,
    DisableHTTPErrorRendering: false,
    RenderPartialsWithoutPrefix: false,
    BufferPool: GenericBufferPool,
})
JSON vs Streaming JSON

By default, Render does not stream JSON to the http.ResponseWriter. It instead marshalls your object into a byte array, and if no errors occurred, writes that byte array to the http.ResponseWriter. If you would like to use the built it in streaming functionality (json.Encoder), you can set the StreamingJSON setting to true. This will stream the output directly to the http.ResponseWriter. Also note that streaming is only implemented in render.JSON and not render.JSONP.

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

Templates can be loaded from an embed.FS.

// ...

//go:embed templates/*.html templates/*.tmpl
var embeddedTemplates embed.FS

// ...

r := render.New(render.Options{
    Directory: "templates",
    FileSystem: &render.EmbedFileSystem{
        FS: embeddedTemplates,
    },
    Extensions: []string{".html", ".tmpl"},
})
// ...

You can also load templates from memory by providing the Asset and AssetNames options, e.g. when generating an asset file using go-bindata.

Layouts

Render provides yield and partial functions for layouts to access:

// ...
r := render.New(render.Options{
    Layout: "layout",
})
// ...
<!-- templates/layout.tmpl -->
<html>
  <head>
    <title>My Layout</title>
    <!-- Render the partial template called `css-$current_template` here -->
    {{ partial "css" }}
  </head>
  <body>
    <!-- render the partial template called `header-$current_template` here -->
    {{ partial "header" }}
    <!-- Render the current template here -->
    {{ yield }}
    <!-- render the partial template called `footer-$current_template` here -->
    {{ partial "footer" }}
  </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>

Partials are defined by individual templates as seen below. The partial template's name needs to be defined as "{partial name}-{template name}".

<!-- templates/home.tmpl -->
{{ define "header-home" }}
<h1>Home</h1>
{{ end }}

{{ define "footer-home"}}
<p>The End</p>
{{ end }}

By default, the template is not required to define all partials referenced in the layout. If you want an error to be returned when a template does not define a partial, set Options.RequirePartials = true.

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"

    "github.com/unrolled/render"
)

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/plain; charset=UTF-8".
    mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) {
        r.Text(w, http.StatusOK, "Plain text here")
    })

    // 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", "World")
    })

    http.ListenAndServe("127.0.0.1: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"

    "github.com/unrolled/render"
)

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/plain; charset=ISO-8859-1".
    mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) {
        r.Text(w, http.StatusOK, "Plain text here")
    })

    // 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", "World")
    })

    http.ListenAndServe("127.0.0.1:3000", mux)
}
Error Handling

The rendering functions return any errors from the rendering engine. By default, they will also write the error to the HTTP response and set the status code to 500. You can disable this behavior so that you can handle errors yourself by setting Options.DisableHTTPErrorRendering: true.

r := render.New(render.Options{
  DisableHTTPErrorRendering: true,
})

//...

err := r.HTML(w, http.StatusOK, "example", "World")
if err != nil{
  http.Redirect(w, r, "/my-custom-500", http.StatusFound)
}

Integration Examples

Echo
// main.go
package main

import (
    "io"
    "net/http"

    "github.com/labstack/echo"
    "github.com/unrolled/render"
)

type RenderWrapper struct { // We need to wrap the renderer because we need a different signature for echo.
    rnd *render.Render
}

func (r *RenderWrapper) Render(w io.Writer, name string, data interface{},c echo.Context) error {
    return r.rnd.HTML(w, 0, name, data) // The zero status code is overwritten by echo.
}

func main() {
    r := &RenderWrapper{render.New()}

    e := echo.New()

    e.Renderer = r

    e.GET("/", func(c echo.Context) error {
        return c.Render(http.StatusOK, "TemplateName", "TemplateData")
    })

    e.Logger.Fatal(e.Start("127.0.0.1:8080"))
}
Gin
// main.go
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/unrolled/render"
)

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

    router := gin.Default()

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

    router.Run("127.0.0.1:8080")
}
Goji
// main.go
package main

import (
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
    "github.com/unrolled/render"
)

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/urfave/negroni"
    "github.com/unrolled/render"
)

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("127.0.0.1:8080")
}
Traffic
// main.go
package main

import (
    "net/http"

    "github.com/pilu/traffic"
    "github.com/unrolled/render"
)

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()  // Defaults to "127.0.0.1:3000".
}

Documentation

Overview

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

package main

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

    "github.com/unrolled/render"
)

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

func main() {
    r := render.New()
    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("/text", func(w http.ResponseWriter, req *http.Request) {
        r.Text(w, http.StatusOK, "Plain text here")
    })

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

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

    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("127.0.0.1:3000", mux)
}

Index

Constants

View Source
const (
	// ContentBinary header value for binary data.
	ContentBinary = "application/octet-stream"
	// ContentHTML header value for HTML data.
	ContentHTML = "text/html"
	// ContentJSON header value for JSON data.
	ContentJSON = "application/json"
	// ContentJSONP header value for JSONP data.
	ContentJSONP = "application/javascript"
	// ContentLength header constant.
	ContentLength = "Content-Length"
	// ContentText header value for Text data.
	ContentText = "text/plain"
	// ContentType header constant.
	ContentType = "Content-Type"
	// 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 io.Writer, 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 EmbedFileSystem added in v1.2.0

type EmbedFileSystem struct {
	embed.FS
}

EmbedFileSystem implements FileSystem on top of an embed.FS.

func (*EmbedFileSystem) Walk added in v1.2.0

func (e *EmbedFileSystem) Walk(root string, walkFn filepath.WalkFunc) error

type Engine

type Engine interface {
	Render(io.Writer, interface{}) error
}

Engine is the generic interface for all responses.

type FileSystem added in v1.0.2

type FileSystem interface {
	Walk(root string, walkFn filepath.WalkFunc) error
	ReadFile(filename string) ([]byte, error)
}

func FS added in v1.4.1

func FS(oriFS fs.FS) FileSystem

FS converts io/fs.FS to FileSystem.

type GenericBufferPool added in v1.1.0

type GenericBufferPool interface {
	Get() *bytes.Buffer
	Put(*bytes.Buffer)
}

GenericBufferPool abstracts buffer pool implementations.

type HTML

type HTML struct {
	Head
	Name      string
	Templates *template.Template
	// contains filtered or unexported fields
}

HTML built-in renderer.

func (HTML) Render

func (h HTML) Render(w io.Writer, binding interface{}) error

Render a HTML response.

type HTMLOptions

type HTMLOptions struct {
	// Layout template name. Overrides Options.Layout.
	Layout string
	// Funcs added to Options.Funcs.
	Funcs template.FuncMap
}

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
	UnEscapeHTML  bool
	Prefix        []byte
	StreamingJSON bool
}

JSON built-in renderer.

func (JSON) Render

func (j JSON) Render(w io.Writer, v interface{}) error

Render a JSON response.

type JSONP

type JSONP struct {
	Head
	Indent   bool
	Callback string
}

JSONP built-in renderer.

func (JSONP) Render

func (j JSONP) Render(w io.Writer, v interface{}) error

Render a JSONP response.

type LocalFileSystem added in v1.0.2

type LocalFileSystem struct{}

func (LocalFileSystem) ReadFile added in v1.0.2

func (LocalFileSystem) ReadFile(filename string) ([]byte, error)

func (LocalFileSystem) Walk added in v1.0.2

func (LocalFileSystem) Walk(root string, walkFn filepath.WalkFunc) error

type Options

type Options struct {
	// Directory to load templates. Default is "templates".
	Directory string
	// FileSystem to access files
	FileSystem FileSystem
	// Asset function to use in place of directory. Defaults to nil.
	Asset func(name string) ([]byte, error)
	// AssetNames function to use in place of directory. Defaults to nil.
	AssetNames func() []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 empty map.
	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
	// If DisableCharset is set to true, it will not append the above Charset value to the Content-Type header. Default is false.
	DisableCharset bool
	// Outputs human readable JSON.
	IndentJSON bool
	// Outputs human readable XML. Default is false.
	IndentXML bool
	// Prefixes the JSON output with the given bytes. Default is false.
	PrefixJSON []byte
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte
	// Allows changing the binary content type.
	BinaryContentType string
	// Allows changing the HTML content type.
	HTMLContentType string
	// Allows changing the JSON content type.
	JSONContentType string
	// Allows changing the JSONP content type.
	JSONPContentType string
	// Allows changing the Text content type.
	TextContentType string
	// Allows changing the XML content type.
	XMLContentType string
	// If IsDevelopment is set to true, this will recompile the templates on every request. Default is false.
	IsDevelopment bool
	// If UseMutexLock is set to true, the standard `sync.RWMutex` lock will be used instead of the lock free implementation. Default is false.
	// Note that when `IsDevelopment` is true, the standard `sync.RWMutex` lock is always used. Lock free is only a production feature.
	UseMutexLock bool
	// Unescape HTML characters "&<>" to their original values. Default is false.
	UnEscapeHTML bool
	// Sets the `Option` value for HTML templates. Defaults to blank ("").
	HTMLTemplateOption string
	// Streams JSON responses instead of marshalling prior to sending. Default is false.
	StreamingJSON bool
	// Require that all partials executed in the layout are implemented in all templates using the layout. Default is false.
	RequirePartials bool
	// Deprecated: Use the above `RequirePartials` instead of this. As of Go 1.6, blocks are built in. Default is false.
	RequireBlocks bool
	// Disables automatic rendering of http.StatusInternalServerError when an error occurs. Default is false.
	DisableHTTPErrorRendering bool
	// Enables using partials without the current filename suffix which allows use of the same template in multiple files. e.g {{ partial "carosuel" }} inside the home template will match carosel-home or carosel.
	// ***NOTE*** - This option should be named RenderPartialsWithoutSuffix as that is what it does. "Prefix" is a typo. Maintaining the existing name for backwards compatibility.
	RenderPartialsWithoutPrefix bool
	// BufferPool to use when rendering HTML templates. If none is supplied
	// defaults to SizedBufferPool of size 32 with 512KiB buffers.
	BufferPool GenericBufferPool
}

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) CompileTemplates added in v1.3.0

func (r *Render) CompileTemplates()

func (*Render) Data

func (r *Render) Data(w io.Writer, status int, v []byte) error

Data writes out the raw bytes as binary data.

func (*Render) HTML

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

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

func (*Render) JSON

func (r *Render) JSON(w io.Writer, status int, v interface{}) error

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

func (*Render) JSONP

func (r *Render) JSONP(w io.Writer, status int, callback string, v interface{}) error

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

func (*Render) Render

func (r *Render) Render(w io.Writer, e Engine, data interface{}) error

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

func (*Render) TemplateLookup

func (r *Render) TemplateLookup(t string) *template.Template

TemplateLookup is a wrapper around template.Lookup and returns the template with the given name that is associated with t, or nil if there is no such template.

func (*Render) Text

func (r *Render) Text(w io.Writer, status int, v string) error

Text writes out a string as plain text.

func (*Render) XML

func (r *Render) XML(w io.Writer, status int, v interface{}) error

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

type SizedBufferPool added in v1.1.0

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

SizedBufferPool implements a pool of bytes.Buffers in the form of a bounded channel. Buffers are pre-allocated to the requested size.

func NewSizedBufferPool added in v1.1.0

func NewSizedBufferPool(size int, alloc int) (bp *SizedBufferPool)

NewSizedBufferPool creates a new BufferPool bounded to the given size. size defines the number of buffers to be retained in the pool and alloc sets the initial capacity of new buffers to minimize calls to make().

The value of alloc should seek to provide a buffer that is representative of most data written to the buffer (i.e. 95th percentile) without being overly large (which will increase static memory consumption). You may wish to track the capacity of your last N buffers (i.e. using an []int) prior to returning them to the pool as input into calculating a suitable alloc value.

func (*SizedBufferPool) Get added in v1.1.0

func (bp *SizedBufferPool) Get() (b *bytes.Buffer)

Get gets a Buffer from the SizedBufferPool, or creates a new one if none are available in the pool. Buffers have a pre-allocated capacity.

func (*SizedBufferPool) Put added in v1.1.0

func (bp *SizedBufferPool) Put(b *bytes.Buffer)

Put returns the given Buffer to the SizedBufferPool.

type Text

type Text struct {
	Head
}

Text built-in renderer.

func (Text) Render

func (t Text) Render(w io.Writer, v interface{}) error

Render a text response.

type XML

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

XML built-in renderer.

func (XML) Render

func (x XML) Render(w io.Writer, 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