render

package
v3.1.0+incompatible Latest Latest
Warning

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

Go to latest
Published: May 2, 2019 License: MIT Imports: 4 Imported by: 7

README

Render

Easily rendering JSON, XML, binary data, and HTML templates responses

Usage

It 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.

package main

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

	"github.com/ifreddyrondon/bastion"
	"github.com/ifreddyrondon/bastion/render"
)

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

func main() {
	app := bastion.New()

	app.Get("/data", func(w http.ResponseWriter, req *http.Request) {
		render.Data.Response(w, http.StatusOK, []byte("Some binary data here."))
	})

	app.Get("/text", func(w http.ResponseWriter, req *http.Request) {
		render.Text.Response(w, http.StatusOK, "Plain text here")
	})

	app.Get("/html", func(w http.ResponseWriter, req *http.Request) {
		render.HTML.Response(w, http.StatusOK, "<h1>Hello World</h1>")
	})

	app.Get("/json", func(w http.ResponseWriter, req *http.Request) {
		render.JSON.Response(w, http.StatusOK, map[string]string{"hello": "json"})
	})

	app.Get("/json-ok", func(w http.ResponseWriter, req *http.Request) {
		// with implicit status 200
		render.JSON.Send(w, map[string]string{"hello": "json"})
	})

	app.Get("/xml", func(w http.ResponseWriter, req *http.Request) {
		render.XML.Response(w, http.StatusOK, ExampleXML{One: "hello", Two: "xml"})
	})

	app.Get("/xml-ok", func(w http.ResponseWriter, req *http.Request) {
		// with implicit status 200
		render.XML.Send(w, ExampleXML{One: "hello", Two: "xml"})
	})

	app.Serve()
}
Renderer
// Renderer interface for managing response payloads.
type Renderer interface {
	// Response encoded responses in the ResponseWriter with the HTTP status code.
	Response(w http.ResponseWriter, code int, response interface{})
}

Implementations:

  • render.Data response []byte with application/octet-stream Content-Type.
  • render.Text response strings with text/plain Content-Type.
  • render.HTML response strings with text/html Content-Type.
  • render.JSON response strings with application/json Content-Type.
  • render.XML response strings with application/xml Content-Type.
APIRenderer

APIRenderer are convenient methods for api responses.

// APIRenderer interface for managing API response payloads.
type APIRenderer interface {
	Renderer
	OKRenderer
	ClientErrRenderer
	ServerErrRenderer
}

// OKRenderer interface for managing success API response payloads.
type OKRenderer interface {
	Send(w http.ResponseWriter, response interface{})
	Created(w http.ResponseWriter, response interface{})
	NoContent(w http.ResponseWriter)
}

// ClientErrRenderer interface for managing API responses when client error.
type ClientErrRenderer interface {
	BadRequest(w http.ResponseWriter, err error)
	NotFound(w http.ResponseWriter, err error)
	MethodNotAllowed(w http.ResponseWriter, err error)
}

// ServerErrRenderer interface for managing API responses when server error.
type ServerErrRenderer interface {
	InternalServerError(w http.ResponseWriter, err error)
}

Implementations:

  • render.JSON response strings with text/html Content-Type.
  • render.XML response strings with text/html Content-Type.
package main

import (
	"net/http"
	"errors"

	"github.com/ifreddyrondon/bastion"
	"github.com/ifreddyrondon/bastion/render"
)

type address struct {
	Address string  `json:"address"`
	Lat     float64 `json:"lat"`
	Lng     float64 `json:"lng"`
}

func h201(w http.ResponseWriter, r *http.Request) {
	a := address{"test address", 1, 1}
	render.JSON.Created(w, a)
}

func h400(w http.ResponseWriter, r *http.Request) {
	e := errors.New("test")
	render.JSON.BadRequest(w, e)
}

func h500(w http.ResponseWriter, r *http.Request) {
	e := errors.New("test")
	render.JSON.InternalServerError(w, e)
}

func main() {
	app := bastion.New()
	app.Get("/201", h201)
	app.Get("/400", h400)
	app.Get("/500", h500)
	app.Serve()
}

With Options:

package main

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

	"github.com/ifreddyrondon/bastion"
	"github.com/ifreddyrondon/bastion/render"
)

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

func jsonHandler(w http.ResponseWriter, r *http.Request) {
	render.
			NewJSON(render.PrettyPrintJSON()).
			Send(w, map[string]string{"hello": "json with options"})
}

func xmlHandler(w http.ResponseWriter, r *http.Request) {
	render.
			NewXML(render.PrettyPrintXML()).
			Send(w, ExampleXML{One: "hello", Two: "xml"})
}

func main() {
	app := bastion.New()
	app.Get("/json", jsonHandler)
	app.Get("/xml", xmlHandler)
	app.Serve()
}

E.g.

Documentation

Index

Constants

View Source
const (
	// DefaultFindHeaderIndex defines the maximum number of characters
	// to go through to find a generic XML header.
	DefaultFindHeaderIndex = 100
	// DefaultPrettyPrintXMLindent defines the number of spaces to pretty print a xml
	DefaultPrettyPrintXMLindent = "    "
	// DefaultPrettyPrintXMLPrefix defines the number of spaces to pretty print a xml
	DefaultPrettyPrintXMLPrefix = "  "
)
View Source
const DefaultPrettyPrintJSONIndent = "  "

DefaultPrettyPrintJSONIndent defines the default number of spaces to pretty print a json.

Variables

View Source
var JSON = NewJSON()

JSON is the default JSON renderer

View Source
var XML = NewXML()

XML is the default XML renderer

Functions

func PrettyPrintJSON

func PrettyPrintJSON() func(*JSONRender)

PrettyPrintJSON set JSONRender encoding indent to DefaultPrettyPrintJSONIndent

func PrettyPrintXML

func PrettyPrintXML() func(*XMLRenderer)

PrettyPrintXML set XML encoding indent to DefaultPrettyPrintJSONIdent

Types

type APIRenderer

type APIRenderer interface {
	Renderer
	OKRenderer
	ClientErrRenderer
	ServerErrRenderer
}

APIRenderer interface for managing API response payloads.

type ByteRenderer

type ByteRenderer interface {
	// Response encoded []byte into ResponseWriter with the HTTP status code.
	Response(w http.ResponseWriter, code int, response []byte)
}

ByteRenderer interface manage []byte responses.

type ByteResponder

type ByteResponder string

ByteResponder response []byte with application/octet-stream Content-Type

const (
	// Data returns a ByteResponder who's Response writes a string into a ResponseWriter
	// with the Content-Type as application/octet-stream.
	Data ByteResponder = "application/octet-stream"
)

func (ByteResponder) Response

func (s ByteResponder) Response(w http.ResponseWriter, code int, response []byte)

Response encoded []byte into ResponseWriter with the HTTP status code.

type ClientErrRenderer

type ClientErrRenderer interface {
	BadRequest(w http.ResponseWriter, err error)
	NotFound(w http.ResponseWriter, err error)
	MethodNotAllowed(w http.ResponseWriter, err error)
}

ClientErrRenderer interface for managing API responses when client error.

type HTTPError

type HTTPError struct {
	Message string `json:"message,omitempty" xml:"message,attr,omitempty"`
	Error   string `json:"error,omitempty" xml:"error,attr,omitempty"`
	Status  int    `json:"status,omitempty" xml:"status,attr,omitempty"`
}

HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(message, err string, status int) *HTTPError

NewHTTPError returns a new HTTPError instance.

type JSONRender

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

JSONRender encode the response as "application/json" content type It implements the Renderer and APIRenderer interface.

func NewJSON

func NewJSON(opts ...func(*JSONRender)) *JSONRender

NewJSON returns a new JSONRender responder instance.

func (*JSONRender) BadRequest

func (j *JSONRender) BadRequest(w http.ResponseWriter, err error)

BadRequest sends a JSONRender-encoded error response in the body of a request with the 400 status code. The response will contains the status 400 and error "Bad Request".

func (*JSONRender) Created

func (j *JSONRender) Created(w http.ResponseWriter, v interface{})

Created sends a JSONRender-encoded v in the body of a request with the 201 status code.

func (*JSONRender) InternalServerError

func (j *JSONRender) InternalServerError(w http.ResponseWriter, err error)

InternalServerError sends a JSONRender-encoded error response in the body of a request with the 500 status code. The response will contains the status 500 and error "Internal Server Error".

func (*JSONRender) MethodNotAllowed

func (j *JSONRender) MethodNotAllowed(w http.ResponseWriter, err error)

MethodNotAllowed sends a JSONRender-encoded error response in the body of a request with the 405 status code. The response will contains the status 405 and error "Method Not Allowed".

func (*JSONRender) NoContent

func (j *JSONRender) NoContent(w http.ResponseWriter)

NoContent sends a v without no content with the 204 status code.

func (*JSONRender) NotFound

func (j *JSONRender) NotFound(w http.ResponseWriter, err error)

NotFound sends a JSONRender-encoded error response in the body of a request with the 404 status code. The response will contains the status 404 and error "Not Found".

func (*JSONRender) Response

func (j *JSONRender) Response(w http.ResponseWriter, code int, v interface{})

Response sends a JSONRender-encoded v in the body of a request with the HTTP status code.

func (*JSONRender) Send

func (j *JSONRender) Send(w http.ResponseWriter, v interface{})

Send sends a JSONRender-encoded v in the body of a request with the 200 status code.

type OKRenderer

type OKRenderer interface {
	Send(w http.ResponseWriter, response interface{})
	Created(w http.ResponseWriter, response interface{})
	NoContent(w http.ResponseWriter)
}

OKRenderer interface for managing success API response payloads.

type Renderer

type Renderer interface {
	// Response encoded responses in the ResponseWriter with the HTTP status code.
	Response(w http.ResponseWriter, code int, response interface{})
}

Renderer describes the interface which needs to be implemented for managing response payloads.

type ServerErrRenderer

type ServerErrRenderer interface {
	InternalServerError(w http.ResponseWriter, err error)
}

ServerErrRenderer interface for managing API responses when server error.

type StringRenderer

type StringRenderer interface {
	// Response encoded string into ResponseWriter with the HTTP status code.
	Response(w http.ResponseWriter, code int, response string)
}

StringRenderer interface manage string responses.

type StringResponder

type StringResponder string

StringResponder response strings

const (
	// Text returns a StringResponder who's Response writes a string into a ResponseWriter
	// with the Content-Type as text/plain.
	Text StringResponder = "text/plain; charset=utf-8"
	// HTML returns a StringResponder who's Response writes a string into a ResponseWriter
	// with the Content-Type as text/html.
	HTML StringResponder = "text/html; charset=utf-8"
)

func (StringResponder) Response

func (s StringResponder) Response(w http.ResponseWriter, code int, response string)

Response encoded responses in the ResponseWriter with the HTTP status code.

type XMLRenderer

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

XMLRenderer encode the response as "application/xml" content type and implement the Renderer and APIRenderer interface.

func NewXML

func NewXML(opts ...func(*XMLRenderer)) *XMLRenderer

NewXML returns a new XML responder instance.

func (*XMLRenderer) BadRequest

func (x *XMLRenderer) BadRequest(w http.ResponseWriter, err error)

BadRequest sends a XML-encoded error response in the body of a request with the 400 status code. The response will contains the status 400 and error "Bad Request".

func (*XMLRenderer) Created

func (x *XMLRenderer) Created(w http.ResponseWriter, v interface{})

Created sends a XML-encoded v in the body of a request with the 201 status code.

func (*XMLRenderer) InternalServerError

func (x *XMLRenderer) InternalServerError(w http.ResponseWriter, err error)

InternalServerError sends a XML-encoded error response in the body of a request with the 500 status code. The response will contains the status 500 and error "Internal Server Error".

func (*XMLRenderer) MethodNotAllowed

func (x *XMLRenderer) MethodNotAllowed(w http.ResponseWriter, err error)

MethodNotAllowed sends a XML-encoded error response in the body of a request with the 405 status code. The response will contains the status 405 and error "Method Not Allowed".

func (*XMLRenderer) NoContent

func (x *XMLRenderer) NoContent(w http.ResponseWriter)

NoContent sends a v without no content with the 204 status code.

func (*XMLRenderer) NotFound

func (x *XMLRenderer) NotFound(w http.ResponseWriter, err error)

NotFound sends a XML-encoded error response in the body of a request with the 404 status code. The response will contains the status 404 and error "Not Found".

func (*XMLRenderer) Response

func (x *XMLRenderer) Response(w http.ResponseWriter, code int, v interface{})

Response marshals 'v' to XML, setting the Content-Type as application/xml. It will automatically prepend a generic XML header (see encoding/xml.Header) if one is not found in the first 100 bytes of 'v'.

func (*XMLRenderer) Send

func (x *XMLRenderer) Send(w http.ResponseWriter, v interface{})

Send sends a XML-encoded v in the body of a request with the 200 status code.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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