render

package
v0.0.0-...-46db650 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2020 License: MIT Imports: 13 Imported by: 0

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"  // or "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()
    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("0.0.0.0: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 BufferPool

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

BufferPool implements a pool of bytes.Buffers in the form of a bounded channel. Pulled from the github.com/oxtoacart/bpool package (Apache licensed).

func NewBufferPool

func NewBufferPool(size int) (bp *BufferPool)

NewBufferPool creates a new BufferPool bounded to the given size.

func (*BufferPool) Get

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

Get gets a Buffer from the BufferPool, or creates a new one if none are available in the pool.

func (*BufferPool) Put

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

Put returns the given Buffer to the BufferPool.

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 Engine

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

Engine is the generic interface for all responses.

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
}

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 Options

type Options struct {
	// Directory to load templates. Default is "templates".
	Directory string
	// 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 [].
	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. 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 of output to XHTML instead of HTML. Default is "text/html".
	HTMLContentType string
	// Unescape HTML characters "&<>" to their original values. Default is false.
	UnEscapeHTML bool
	// 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
}

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 io.Writer, status int, v []byte) error

Data writes out the raw bytes as binary data.

func (*Render) DoCompileTemplates

func (r *Render) DoCompileTemplates()

DoCompileTemplates 手动进行调用

func (*Render) HTML

func (r *Render) HTML(w io.Writer, req *http.Request, status int, name string, binding interface{}, before func(), query string, 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 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