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
- Variables
- type Data
- type Delims
- type EmbedFileSystem
- type Engine
- type FileSystem
- type GenericBufferPool
- type HTML
- type HTMLOptions
- type Head
- type JSON
- type JSONEncoder
- type JSONP
- type LocalFileSystem
- type Options
- type Render
- func (r *Render) CompileTemplates()
- func (r *Render) Data(w io.Writer, status int, v []byte) error
- func (r *Render) HTML(w io.Writer, status int, name string, binding interface{}, ...) error
- func (r *Render) JSON(w io.Writer, status int, v interface{}) error
- func (r *Render) JSONP(w io.Writer, status int, callback string, v interface{}) error
- func (r *Render) Render(w io.Writer, e Engine, data interface{}) error
- func (r *Render) TemplateLookup(t string) *template.Template
- func (r *Render) Text(w io.Writer, status int, v string) error
- func (r *Render) XML(w io.Writer, status int, v interface{}) error
- type SizedBufferPool
- type Text
- type XML
Constants ¶
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 ¶
var ( ErrYieldNoLayoutDefined = errors.New("yield called with no layout defined") ErrBlockNoLayoutDefined = errors.New("block called with no layout defined") )
Functions ¶
This section is empty.
Types ¶
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
EmbedFileSystem implements FileSystem on top of an embed.FS.
type FileSystem ¶ added in v1.0.2
type GenericBufferPool ¶ added in v1.1.0
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.
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 JSON ¶
type JSON struct { Head Indent bool UnEscapeHTML bool Prefix []byte StreamingJSON bool Encoder func(w io.Writer) JSONEncoder }
JSON built-in renderer.
type JSONEncoder ¶ added in v1.7.0
type JSONEncoder interface { Encode(v interface{}) error SetEscapeHTML(on bool) SetIndent(prefix, indent string) }
JSONEncoder is the interface for encoding/json.Encoder.
type LocalFileSystem ¶ added in v1.0.2
type LocalFileSystem struct{}
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 "carousel" }} inside the home template will match carousel-home or carousel. // ***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 // Custom JSON Encoder. Defaults to encoding/json.NewEncoder. JSONEncoder func(w io.Writer) JSONEncoder }
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 (*Render) CompileTemplates ¶ added in v1.3.0
func (r *Render) CompileTemplates()
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) Render ¶
Render is the generic function called by XML, JSON, Data, HTML, and can be called by custom implementations.
func (*Render) TemplateLookup ¶
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.
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.