Documentation ¶
Overview ¶
Package render helps manage HTTP request / response payloads.
Every well-designed, robust and maintainable Web Service / REST API also needs well-_defined_ request and response payloads. Together with the endpoint handlers, the request and response payloads make up the contract between your server and the clients calling on it.
This is where `render` comes in - offering a few simple helpers to provide a simple pattern for managing payload encoding and decoding.
Index ¶
- Constants
- Variables
- func Attachment(w http.ResponseWriter, r *http.Request, fullPath string)
- func Bind(r *http.Request, v interface{}) error
- func Blob(w http.ResponseWriter, v []byte, params ...interface{})
- func DecodeForm(r io.Reader, v interface{}) error
- func DecodeJSON(r io.Reader, v interface{}) error
- func DecodeXML(r io.Reader, v interface{}) error
- func DefaultDecoder(r *http.Request, v interface{}) (err error)
- func DefaultErrorRespond(r *http.Request, err error) interface{}
- func DefaultPaginationBody(r *http.Request, p Pagination, v interface{}) interface{}
- func DefaultResponder(w http.ResponseWriter, r *http.Request, v interface{}, params ...interface{})
- func Error(w http.ResponseWriter, r *http.Request, err error, params ...interface{})
- func File(w http.ResponseWriter, r *http.Request, fullPath string)
- func HTML(w http.ResponseWriter, v string, params ...interface{})
- func Inline(w http.ResponseWriter, r *http.Request, fullPath string)
- func JSON(w http.ResponseWriter, v interface{}, params ...interface{})
- func NoContent(w http.ResponseWriter)
- func PlainText(w http.ResponseWriter, v string, params ...interface{})
- func Render(w http.ResponseWriter, r *http.Request, v interface{}, params ...interface{})
- func Stream(w http.ResponseWriter, r *http.Request, v interface{})
- func XML(w http.ResponseWriter, v interface{}, params ...interface{})
- type ContentType
- type Decoder
- type Encoder
- type ErrorResponse
- type HTTPError
- type Pagination
Constants ¶
const ( ApplicationXML = "application/xml" ApplicationXHTML = "application/xhtml+xml" ApplicationJSON = "application/json" ApplicationJSONExt = "application/json; charset=utf-8" ApplicationFormURL = "application/x-www-form-urlencoded" TextPlain = "text/plain" TextHTML = "text/html" TextXML = "text/xml" TextJavascript = "text/javascript" TextEventStream = "text/event-stream" )
MIME types for handling request/response body
const ( ContentTypeHeader = "Content-Type" AcceptHeader = "Accept" )
Header names used in request/response
Variables ¶
var ( // JSONDecoder is a package-level variable set to our default JSON decoder // function. JSONDecoder = DefaultJSONDecoder // XMLDecoder is a package-level variable set to our default XML decoder // function. XMLDecoder = DefaultXMLDecoder // FormDecoder is a package-level variable set to our default Form decoder // function. FormDecoder = DefaultFormDecoder )
var ( // ErrInvalidToken is returned when the api request token is invalid. ErrInvalidToken = errors.New("invalid or missing token") ErrUnauthorized = errors.New("Unauthorized") // ErrForbidden is returned when user access is forbidden. ErrForbidden = errors.New("Forbidden") // ErrNotFound is returned when a resource is not found. ErrNotFound = errors.New("not found") )
var ( // PageParam is query name param for current page PageParam = "page" // PerPageParam is number of items per page PerPageParam = "per_page" // PerPageDefault sets default number of items on response PerPageDefault = 25 // Linkf is format for Link headers Linkf = `<%s>; rel="%s"` // PaginationInHeader write pagination in header PaginationInHeader = true // PaginationBody generates pagination in body PaginationBody = DefaultPaginationBody )
var ( // JSONEncoder is a package variable set to default JSON encoder JSONEncoder = DefaultJSONEncoder // XMLEncoder is a package variable set to default XML encoder XMLEncoder = DefaultXMLEncoder )
var Decode = DefaultDecoder
Decode is a package-level variable set to our DefaultDecoder. We do this because it allows you to set render.Decode to another function with the same function signature, while also utilizing the render.DefaultDecoder() function itself. Effectively, allowing you to easily add your own logic to the package defaults. For example, maybe you want to impose a limit on the number of bytes allowed to be read from the request body.
var DefaultContentType = ContentTypeJSON
DefaultContentType is a package-level variable set to our default content type
var ErrUnableToParseContentType = errors.New("render: unable to automatically decode the request content type")
ErrUnableToParseContentType is an error for unknown content type
var ErrorMap = map[error]int{ ErrInvalidToken: http.StatusBadRequest, ErrUnauthorized: http.StatusUnauthorized, ErrForbidden: http.StatusForbidden, ErrNotFound: http.StatusNotFound, }
ErrorMap contains predefined errors with assigned status code.
var Respond = DefaultResponder
Respond is a package-level variable set to our default Responder. We do this because it allows you to set render.Respond to another function with the same function signature, while also utilizing the render.Responder() function itself. Effectively, allowing you to easily add your own logic to the package defaults. For example, maybe you want to test if v is an error and respond differently, or log something before you respond.
var TreatError = DefaultErrorRespond
TreatError is a package-level variable set to default function with basic error message response. Any error provided will have just a simple struct with field message describing the error. Developer can create custom function for treating error responses, for example:
render.TreatError = func(r *http.Request, err error) interface{} { cerr := &CustomError{} if errors.As(err, &cerr) { return &customResponse{ Message: cerr.Err, Version: "1.0", ... } return &HTTPError{ Message: "some error message", Status: http.StatusCreated, } }
and render.Error(w, r, err) will create response based of your treat function.
Functions ¶
func Attachment ¶
func Attachment(w http.ResponseWriter, r *http.Request, fullPath string)
Attachment sends a response as attachment, prompting client to save the file.
func Blob ¶
func Blob(w http.ResponseWriter, v []byte, params ...interface{})
Blob writes raw bytes to the response, the default Content-Type as application/octet-stream, params is optional which can be int or string type. Int will provide status code and string is for header pair values
for example:
Blob(w, v) Blob(w, v, http.StatusOK) Blob(w, v, http.StatusOK, "Content-Type", "application/json") or using constants ContentTypeHeader and ApplicationJSON Blob(w, v, http.StatusOK, "Content-Type", "application/json") Blob(w, v, "Content-Type", "application/json") Blob(w, v, "Content-Type", "application/json", http.StatusOK) you can pass http.Header struct
Blob(w, v, http.Header{ "Content-Type": []string{"application/json"}, }, http.StatusOK)
the order of the parameters does not matter.
func DecodeForm ¶
DecodeForm decodes a given reader into an interface using the form decoder.
func DecodeJSON ¶
DecodeJSON decodes a given reader into an interface using the json decoder.
func DefaultDecoder ¶
DefaultDecoder detects the correct decoder for use on an HTTP request and marshals into a given interface.
func DefaultErrorRespond ¶
DefaultErrorRespond returns ErrorResponse object for later processing
func DefaultPaginationBody ¶ added in v0.3.0
func DefaultPaginationBody(r *http.Request, p Pagination, v interface{}) interface{}
DefaultPaginationBody returns custom pagination body
func DefaultResponder ¶
func DefaultResponder(w http.ResponseWriter, r *http.Request, v interface{}, params ...interface{})
DefaultResponder handles streaming JSON and XML responses, automatically setting the Content-Type based on request headers or query param `format`. Default content type is JSON.
func Error ¶
func Error(w http.ResponseWriter, r *http.Request, err error, params ...interface{})
Error renders response body with content type based on Accept header of request. Status codes must be >= 400.
func File ¶
func File(w http.ResponseWriter, r *http.Request, fullPath string)
File sends a response with the content of the file.
func HTML ¶
func HTML(w http.ResponseWriter, v string, params ...interface{})
HTML writes a string to the response, setting the Content-Type as text/html.
func Inline ¶
func Inline(w http.ResponseWriter, r *http.Request, fullPath string)
Inline sends a response as inline, opening the file in the browser.
func JSON ¶
func JSON(w http.ResponseWriter, v interface{}, params ...interface{})
JSON marshals 'v' to JSON, automatically escaping HTML and setting the Content-Type as application/json.
func NoContent ¶
func NoContent(w http.ResponseWriter)
NoContent returns a HTTP 204 "No Content" response.
func PlainText ¶
func PlainText(w http.ResponseWriter, v string, params ...interface{})
PlainText writes a string to the response, setting the Content-Type as text/plain.
func Render ¶
func Render(w http.ResponseWriter, r *http.Request, v interface{}, params ...interface{})
Render renders payload and respond to the client request.
func Stream ¶
func Stream(w http.ResponseWriter, r *http.Request, v interface{})
Stream sends a streaming response with status code and content type.
func XML ¶
func XML(w http.ResponseWriter, v interface{}, params ...interface{})
XML marshals 'v' to JSON, 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'.
Types ¶
type ContentType ¶
type ContentType int
ContentType is an enumeration of common HTTP content types.
const ( ContentTypeUnknown ContentType = iota ContentTypePlainText ContentTypeHTML ContentTypeJSON ContentTypeXML ContentTypeForm ContentTypeEventStream )
ContentTypes handled by this package.
func GetAcceptedContentType ¶
func GetAcceptedContentType(r *http.Request) ContentType
GetAcceptedContentType reads Accept header from request and returns ContentType
func GetContentType ¶
func GetContentType(s string) ContentType
GetContentType returns ContentType value based on input s
func GetRequestContentType ¶
func GetRequestContentType(r *http.Request) ContentType
GetRequestContentType is a helper function that returns ContentType based on context or request headers.
type Decoder ¶ added in v0.2.0
type Decoder interface {
Decode(v interface{}) error
}
Decoder decodes data from reader
func DefaultFormDecoder ¶ added in v0.2.0
DefaultFormDecoder returns new Form decoder for decoding form data.
func DefaultJSONDecoder ¶ added in v0.2.0
DefaultJSONDecoder returns new JSON decoder for decoding JSON data.
func DefaultXMLDecoder ¶ added in v0.2.0
DefaultXMLDecoder returns new XML decoder for decoding XML data.
type Encoder ¶ added in v0.2.0
type Encoder interface {
Encode(v interface{}) error
}
Encoder provide method for encoding reader data
func DefaultJSONEncoder ¶ added in v0.2.0
DefaultJSONEncoder creates default JSON encoder
func DefaultXMLEncoder ¶ added in v0.2.0
DefaultXMLEncoder creates default XML encoder
type ErrorResponse ¶
type ErrorResponse struct {
Message string `json:"message" xml:"message"`
}
ErrorResponse represents a json-encoded API error.
type Pagination ¶ added in v0.3.0
type Pagination struct { Total int // contains filtered or unexported fields }
Pagination holds all page related data
func PaginationFromRequest ¶ added in v0.3.0
func PaginationFromRequest(r *http.Request) Pagination
PaginationFromRequest loads data from url like: per_page, page etc.
func (Pagination) Page ¶ added in v0.3.0
func (p Pagination) Page() int
Page returns non exported page value
func (Pagination) Render ¶ added in v0.3.0
func (p Pagination) Render(w http.ResponseWriter, r *http.Request, v interface{}, params ...interface{})
Render renders payload and respond to the client request.
func (Pagination) Size ¶ added in v0.3.0
func (p Pagination) Size() int
Size returns size (per_page) value