Documentation
¶
Overview ¶
Package render provides a lightweight, allocation-free rendering system for Go.
All renderers implement a single two-method interface:
type Renderer interface {
ContentType() string
Render(ctx context.Context, w io.Writer, data any, opts Options) error
}
Options is a plain value struct — pass it by value, no allocations on the hot path:
opts := render.Options{Pretty: true, Indent: " "}
err := render.JSON().Render(ctx, w, data, opts)
Use render.NoOptions (the zero value) when no configuration is needed:
err := render.JSON().Render(ctx, w, data, render.NoOptions)
Built-in renderers: JSON, XML, CSV, Text, HTML, Binary, YAML, Markdown, Gzip, Buffer, Cache, Multi, Pipe.
For HTML and text template rendering, see the tmpl sub-package.
Index ¶
- Constants
- Variables
- func ApplyTimeout(ctx context.Context, opts Options) (context.Context, context.CancelFunc)
- func CheckContext(ctx context.Context) error
- type BufferConfig
- type BufferRenderer
- type CacheConfig
- type JSONConfig
- type MarkdownConfig
- type Options
- type Renderer
- func Binary() Renderer
- func CSV() Renderer
- func Cache(r Renderer) Renderer
- func Gzip() Renderer
- func HTML() Renderer
- func JSON() Renderer
- func Markdown() Renderer
- func Multi(renderer Renderer, writers ...io.Writer) Renderer
- func NewCache(r Renderer, cfg CacheConfig) Renderer
- func NewJSON(c JSONConfig) Renderer
- func NewMarkdown(c MarkdownConfig) Renderer
- func NewXML(c XMLConfig) Renderer
- func NewYAML(c YAMLConfig) Renderer
- func Pipe(renderers ...Renderer) Renderer
- func Text() Renderer
- func XML() Renderer
- func YAML() Renderer
- type XMLConfig
- type YAMLConfig
Examples ¶
Constants ¶
const ( ContentTypeJSON = "application/json; charset=utf-8" ContentTypeXML = "application/xml; charset=utf-8" ContentTypeText = "text/plain; charset=utf-8" ContentTypeHTML = "text/html; charset=utf-8" ContentTypeCSV = "text/csv; charset=utf-8" ContentTypeBinary = "application/octet-stream" ContentTypeYAML = "application/yaml; charset=utf-8" )
ContentTypes groups the MIME type constants used by the built-in renderers.
Variables ¶
var ( // ErrInvalidContentType indicates that the content type format is invalid ErrInvalidContentType = errors.New("invalid content type") // ErrNegativeTimeout indicates that a negative duration was provided for timeout ErrNegativeTimeout = errors.New("timeout cannot be negative") // ErrInvalidParam indicates that a parameter value is invalid ErrInvalidParam = errors.New("invalid parameter value") // ErrRenderFailed indicates that the rendering process failed. // This can happen due to various reasons like I/O errors or formatting issues. ErrRenderFailed = errors.New("render failed") // ErrTemplateNotFound indicates that the requested template does not exist // in the template store or cannot be accessed. ErrTemplateNotFound = errors.New("template not found") // ErrInvalidData indicates that the provided data cannot be processed // by the renderer. This might happen when the data type is incompatible // with the chosen renderer. ErrInvalidData = errors.New("invalid data for renderer") )
Package level errors that can be returned by Options validation
var NoOptions = Options{}
NoOptions is the reusable zero-value Options preset.
Functions ¶
func ApplyTimeout ¶ added in v0.3.0
ApplyTimeout returns a derived context with a timeout if one is configured in opts. If no timeout is set, it returns the original context with a no-op cancel function. The cancel function must always be called to release resources, typically via defer.
func CheckContext ¶
CheckContext verifies if the context is still valid. It returns nil if the context is valid, or the context error if it's done.
Types ¶
type BufferConfig ¶
type BufferConfig struct {
// InitialSize specifies the initial size of the buffer in bytes.
// Setting this to a value close to the expected output size can improve
// performance by reducing buffer reallocations.
// If 0, the default buffer size is used.
InitialSize int
// PostRender defines a function to transform or validate the rendered content
// before it is written to the output. This can be used for tasks like:
// - Content minification
// - Data compression
// - Schema validation
// - Content transformation
// - Metadata injection
// If nil, the content is written as-is.
PostRender func([]byte) ([]byte, error)
}
BufferConfig holds configuration for the BufferRenderer. It allows customization of initial buffer size and post-processing functionality.
type BufferRenderer ¶
type BufferRenderer struct {
// contains filtered or unexported fields
}
BufferRenderer provides buffered rendering capabilities with optional post-processing. It wraps another renderer and buffers its output before writing, which allows: - Complete content validation before writing - Content transformation through post-processing - Error handling without partial writes
func Buffer ¶
func Buffer(r Renderer) *BufferRenderer
Buffer creates a new BufferRenderer with default configuration. This is the recommended constructor for simple buffering without post-processing.
Example:
// Create a buffered JSON renderer
renderer := Buffer(JSON())
file, _ := os.Create("output.json")
renderer.Render(file, data)
func NewBuffer ¶
func NewBuffer(r Renderer, c BufferConfig) *BufferRenderer
NewBuffer creates a BufferRenderer with custom configuration. Use this when you need to specify buffer size or add post-processing.
Example:
// Create a renderer with post-processing
renderer := NewBuffer(JSON(), BufferConfig{
InitialSize: 4096,
PostRender: func(data []byte) ([]byte, error) {
// Perform content transformation
return transform(data)
},
})
func (*BufferRenderer) ContentType ¶ added in v0.14.0
func (r *BufferRenderer) ContentType() string
ContentType returns the MIME type reported by the wrapped renderer.
func (*BufferRenderer) Render ¶
Render implements buffered rendering with context support. The rendering process follows these steps: 1. Creates a buffer (pre-allocated if InitialSize > 0) 2. Renders content to the buffer using the wrapped renderer 3. If configured, applies post-processing to the buffered content 4. Writes the final content to the provided writer
This approach ensures that no partial content is written if an error occurs during rendering or post-processing.
type CacheConfig ¶ added in v0.11.0
type CacheConfig struct {
TTL time.Duration // Duration before the cache expires. 0 means permanent.
}
CacheConfig holds configuration for the cache renderer.
type JSONConfig ¶
type JSONConfig struct {
// Controls HTML character escaping
EscapeHTML bool
// Custom prefix for JSON output
Prefix string
// Custom indentation for JSON output
Indent string
// JSONP function name (if empty, standard JSON is used)
Padding string
}
JSONConfig defines configuration for JSON renderer. It provides JSON-specific settings that are set during initialization.
type MarkdownConfig ¶ added in v0.9.0
type MarkdownConfig struct {
// GFM enables GitHub Flavored Markdown extensions:
// tables, strikethrough, autolinks, and task lists.
GFM bool
// Unsafe allows raw HTML inside Markdown content.
// Disabled by default to prevent XSS vulnerabilities.
Unsafe bool
}
MarkdownConfig defines configuration for the Markdown renderer.
type Options ¶
type Options struct {
// Timeout limits how long rendering may take. Zero means no limit.
Timeout time.Duration
// Name selects the template to execute (tmpl renderers only).
Name string
// Pretty enables human-readable, indented output.
Pretty bool
// Indent sets the indentation string for JSON and XML output.
// Ignored when Pretty is false.
Indent string
// Prefix sets the per-line prefix string for JSON and XML output.
// Ignored when Pretty is false.
Prefix string
// LineEnding overrides the default line ending character(s).
// Used by the CSV renderer. Common values: "\n", "\r\n".
LineEnding string
// Args holds printf-style arguments for text rendering.
// Used by the Text renderer when the data string contains verbs.
Args []any
// Separator sets the CSV field separator rune. Default is ','.
Separator rune
// Padding sets the JSONP callback function name (JSON renderer only).
// When non-empty the output is wrapped: callback(json).
Padding string
// Headers contains additional response headers to set.
// Nil by default — allocate only when custom headers are needed.
Headers map[string][]string
}
Options configures a single render call. It is passed by value so no allocation occurs on the hot path. Zero value is valid and means "use renderer defaults".
func WithHeader ¶ added in v0.14.0
WithHeader returns a copy of opts with the given header key/value added.
func WithIndent ¶ added in v0.14.0
WithIndent returns a copy of opts with Indent set to s.
func WithPretty ¶ added in v0.14.0
WithPretty returns a copy of opts with Pretty enabled.
type Renderer ¶
type Renderer interface {
ContentType() string
// Render writes the rendered content to w using the provided context and options.
// The context is checked for cancellation before rendering begins.
Render(ctx context.Context, w io.Writer, data any, opts Options) error
}
Renderer defines a common interface for all renderers in the system. It provides a unified way to render content with or without context, using functional options for configuration.
The interface is designed to be simple yet flexible, allowing different types of renderers (JSON, XML, HTML, etc.) to share the same API while implementing their specific rendering logic.
func Binary ¶ added in v0.7.0
func Binary() Renderer
Binary creates a renderer for raw binary content such as files, images or PDFs. It sets the Content-Type to application/octet-stream by default. Use the Attachment option to set a Content-Disposition header for file downloads.
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
_ = render.Binary().Render(context.Background(), os.Stdout, []byte("binary content"), render.NoOptions)
}
Output: binary content
func CSV ¶
func CSV() Renderer
CSV creates a new CSV renderer with default configuration: - Comma as delimiter - Standard line endings based on encoding/csv defaults This is the recommended constructor for most use cases.
func Cache ¶ added in v0.11.0
Cache creates a renderer that caches the output permanently. Use it for truly static data that never changes.
Example:
var cached = render.Cache(render.JSON())
func handler(w http.ResponseWriter, r *http.Request) {
cached.Render(w, data, render.WriteResponse(w))
}
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
r := render.Cache(render.JSON())
_ = r.Render(context.Background(), os.Stdout, "hello", render.NoOptions)
_ = r.Render(context.Background(), os.Stdout, "hello", render.NoOptions)
}
Output: "hello" "hello"
func Gzip ¶ added in v0.10.0
func Gzip() Renderer
Gzip creates a renderer that compresses input data using gzip. It expects []byte as input — use it as the last step in a Pipe.
Example:
render.Pipe(
render.JSON(),
render.Gzip(),
).Render(w, data,
render.EncodingGzip(),
render.WriteResponse(w),
)
Example ¶
package main
import (
"bytes"
"context"
"github.com/nanoninja/render"
)
func main() {
var buf bytes.Buffer
_ = render.Pipe(
render.JSON(),
render.Gzip(),
).Render(context.Background(), &buf, map[string]string{"message": "hello"}, render.NoOptions)
}
Output:
func HTML ¶ added in v0.6.0
func HTML() Renderer
HTML creates a renderer that writes raw HTML content. It sets the Content-Type to text/html automatically. For template-based rendering, use the tmpl sub-package instead.
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
_ = render.HTML().Render(context.Background(), os.Stdout, "<h1>Hello</h1>", render.NoOptions)
}
Output: <h1>Hello</h1>
func JSON ¶
func JSON() Renderer
JSON creates a new JSONRenderer with safe default configuration: - HTML escaping enabled for web safety - Standard 2-space indentation This is the recommended constructor for most use cases.
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
data := map[string]string{"message": "hello"}
_ = render.JSON().Render(context.Background(), os.Stdout, data, render.NoOptions)
}
Output: {"message":"hello"}
func Markdown ¶ added in v0.9.0
func Markdown() Renderer
Markdown creates a new Markdown renderer with default configuration. It converts Markdown input to HTML and sets the Content-Type to text/html.
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
_ = render.Markdown().Render(context.Background(), os.Stdout, "# Hello", render.NoOptions)
}
Output: <h1>Hello</h1>
func Multi ¶ added in v0.8.0
Multi creates a renderer that writes to the primary writer and all additional writers simultaneously. It wraps an existing renderer and duplicates its output to every destination.
Example:
// Write JSON to the response and a log buffer at the same time var log bytes.Buffer render.Multi(render.JSON(), &log).Render(w, data)
Example ¶
package main
import (
"bytes"
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
var log bytes.Buffer
_ = render.Multi(render.JSON(), &log).Render(context.Background(), os.Stdout, map[string]string{
"key": "value",
}, render.NoOptions)
}
Output: {"key":"value"}
func NewCache ¶ added in v0.11.0
func NewCache(r Renderer, cfg CacheConfig) Renderer
NewCache creates a renderer that caches the output with optional TTL. If TTL is zero, the cache never expires.
Example:
renderer := render.NewCache(render.JSON(), render.CacheConfig{
TTL: 5 * time.Minute,
})
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
r := render.NewCache(render.JSON(), render.CacheConfig{
TTL: 5 * 60 * 1000000000,
})
_ = r.Render(context.Background(), os.Stdout, map[string]string{"status": "ok"}, render.NoOptions)
}
Output: {"status":"ok"}
func NewJSON ¶
func NewJSON(c JSONConfig) Renderer
NewJSON creates a JSONRenderer with custom configuration. Use this when you need specific JSON behaviors different from defaults.
func NewMarkdown ¶ added in v0.9.0
func NewMarkdown(c MarkdownConfig) Renderer
NewMarkdown creates a Markdown renderer with custom configuration. Use MarkdownConfig to enable GFM extensions or allow raw HTML.
func NewXML ¶
NewXML creates a XMLRenderer with custom configuration. Use this when you need specific XML behaviors different from defaults.
func NewYAML ¶ added in v0.5.0
func NewYAML(c YAMLConfig) Renderer
NewYAML creates a YAML renderer with custom configuration.
func Pipe ¶ added in v0.8.0
Pipe creates a renderer that chains multiple renderers in sequence. The output of each renderer becomes the input data for the next one. The final renderer writes directly to w.
Example:
render.Pipe(
render.JSON(),
myGzipRenderer,
).Render(w, data)
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
_ = render.Pipe(
render.Text(),
).Render(context.Background(), os.Stdout, "Hello", render.NoOptions)
}
Output: Hello
func Text ¶
func Text() Renderer
Text creates a new TextRenderer instance configured with default options. The renderer uses text/plain content type by default which can be overridden using render options.
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
_ = render.Text().Render(context.Background(), os.Stdout, "Hello, Gopher!", render.NoOptions)
}
Output: Hello, Gopher!
func XML ¶
func XML() Renderer
XML creates a new XMLRenderer with safe default configuration. Default settings include: - Standard 2-space indentation - XML header included This is the recommended constructor for most use cases.
func YAML ¶ added in v0.5.0
func YAML() Renderer
YAML creates a new YAML renderer with safe default configuration: - 2-space indentation This is the recommended constructor for most use cases.
Example ¶
package main
import (
"context"
"os"
"github.com/nanoninja/render"
)
func main() {
data := map[string]string{"message": "hello"}
_ = render.YAML().Render(context.Background(), os.Stdout, data, render.NoOptions)
}
Output: message: hello
type XMLConfig ¶
type XMLConfig struct {
// Prefix specifies the string to prepend at the start of each line.
// This is particularly useful when embedding XML within another format.
Prefix string
// Indent specifies the string used for each level of indentation.
// Common values are spaces (" ") or tabs ("\t").
Indent string
// Header controls whether to include the XML declaration at the start.
// When true, adds <?xml version="1.0" encoding="UTF-8"?>.
Header bool
}
XMLConfig defines configuration options for XML rendering. It allows customization of escaping, indentation, and XML header inclusion.
type YAMLConfig ¶ added in v0.5.0
type YAMLConfig struct {
// Indent specifies the number of spaces used for indentation.
// Defaults to 2 if not set.
Indent int
}
YAMLConfig defines configuration for the YAML renderer.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package tmpl provides Go template rendering on top of the render.Renderer interface.
|
Package tmpl provides Go template rendering on top of the render.Renderer interface. |
|
loader
Package loader provides different template loading strategies for the tmpl package.
|
Package loader provides different template loading strategies for the tmpl package. |