rest

package module
v0.1.1-0...-8ade113 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2020 License: MIT Imports: 5 Imported by: 6

README

rest GoDoc

Package rest implements a framework for creating a JSON REST API.

It automatically serializes the responses as JSON and provides the user with the ability to implement a clearer flow of control within the handler thanks to encapsulating all calls to the response writer within a single return value from the handler.

func handler(r *http.Request) rest.RestResponse {
    value, err := someFunction()
    if err != nil {
        return rest.InternalServerError
    }
    return rest.NewResponse(value)
}

Documentation

Overview

Package rest implements a framework for creating a JSON REST API. It automatically serializes the responses as JSON and provides the user with the ability to implement a clearer flow of control within the handler thanks to encapsulating all calls to the response writer within a single return value from the handler.

func handler(r *http.Request) rest.RestResponse {
	value, err := someFunction()
	if err != nil {
		return rest.InternalServerError
	}
	return rest.NewResponse(value)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest                   = NewError(http.StatusBadRequest, "Bad request.")
	ErrUnauthorized                 = NewError(http.StatusUnauthorized, "Unauthorized.")
	ErrPaymentRequired              = NewError(http.StatusPaymentRequired, "Payment required.")
	ErrForbidden                    = NewError(http.StatusForbidden, "Forbidden.")
	ErrNotFound                     = NewError(http.StatusForbidden, "Not found.")
	ErrMethodNotAllowed             = NewError(http.StatusMethodNotAllowed, "Method not allowed.")
	ErrNotAcceptable                = NewError(http.StatusNotAcceptable, "Not acceptable.")
	ErrProxyAuthRequired            = NewError(http.StatusProxyAuthRequired, "Proxy auth required.")
	ErrRequestTimeout               = NewError(http.StatusRequestTimeout, "Request timeout.")
	ErrConflict                     = NewError(http.StatusConflict, "Conflict.")
	ErrGone                         = NewError(http.StatusGone, "Gone.")
	ErrLengthRequired               = NewError(http.StatusLengthRequired, "Length required.")
	ErrPreconditionFailed           = NewError(http.StatusPreconditionFailed, "Precondition failed.")
	ErrRequestEntityTooLarge        = NewError(http.StatusRequestEntityTooLarge, "Request entity too large.")
	ErrRequestURITooLong            = NewError(http.StatusRequestURITooLong, "Request URI too long.")
	ErrUnsupportedMediaType         = NewError(http.StatusUnsupportedMediaType, "Unsupported media type.")
	ErrRequestedRangeNotSatisfiable = NewError(http.StatusRequestedRangeNotSatisfiable, "Requested range not satisfiable.")
	ErrExpectationFailed            = NewError(http.StatusExpectationFailed, "Expectation failed.")
	ErrTeapot                       = NewError(http.StatusTeapot, "I'm a teapot.")
	ErrMisdirectedRequest           = NewError(http.StatusMisdirectedRequest, "Misredirected request.")
	ErrUnprocessableEntity          = NewError(http.StatusUnprocessableEntity, "Unprocessable entity.")
	ErrLocked                       = NewError(http.StatusLocked, "Locked.")
	ErrFailedDependency             = NewError(http.StatusFailedDependency, "Failed dependency.")
	ErrTooEarly                     = NewError(http.StatusTooEarly, "Too early.")
	ErrUpgradeRequired              = NewError(http.StatusUpgradeRequired, "Upgrade required.")
	ErrPreconditionRequired         = NewError(http.StatusPreconditionRequired, "Precondition required.")
	ErrTooManyRequests              = NewError(http.StatusTooManyRequests, "Too many requests.")
	ErrRequestHeaderFieldsTooLarge  = NewError(http.StatusRequestHeaderFieldsTooLarge, "Request header fields too large.")
	ErrUnavailableForLegalReasons   = NewError(http.StatusUnavailableForLegalReasons, "Unavailable for legal reasons.")
)

Predefined 4xx client errors.

View Source
var (
	ErrInternalServerError           = NewError(http.StatusInternalServerError, "Internal server error.")
	ErrNotImplemented                = NewError(http.StatusNotImplemented, "Not implemented.")
	ErrBadGateway                    = NewError(http.StatusBadGateway, "Bad gateway.")
	ErrServiceUnavailable            = NewError(http.StatusServiceUnavailable, "Service unavailable.")
	ErrGatewayTimeout                = NewError(http.StatusGatewayTimeout, "Gateway timeout.")
	ErrHTTPVersionNotSupported       = NewError(http.StatusHTTPVersionNotSupported, "HTTP version not supported.")
	ErrVariantAlsoNegotiates         = NewError(http.StatusVariantAlsoNegotiates, "Variant also negotiates.")
	ErrInsufficientStorage           = NewError(http.StatusInsufficientStorage, "Insufficient storage.")
	ErrLoopDetected                  = NewError(http.StatusLoopDetected, "Loop detected.")
	ErrNotExtended                   = NewError(http.StatusNotExtended, "Not extended.")
	ErrNetworkAuthenticationRequired = NewError(http.StatusNetworkAuthenticationRequired, "Network authentication required.")
)

Predefined 5xx server errors.

Functions

func Call

func Call(w http.ResponseWriter, r *http.Request, handler HandlerFunc) error

Call executes the provided handler passing it the provided request. The response returned from the handler is written to the provided response writer. In most cases you should be using Wrap instead of calling this method directly.

func Wrap

func Wrap(handler HandlerFunc) http.HandlerFunc

Wrap encapsulates the provided handler to make it compatibile with net/http.

Example
package main

import (
	"net/http"
	"net/http/httptest"

	"github.com/boreq/rest"
)

func main() {
	handler := func(r *http.Request) rest.RestResponse {
		return rest.NewResponse("response").WithHeader("X-Clacks-Overhead", "GNU Terry Pratchett")
	}

	server := httptest.NewServer(rest.Wrap(handler))
	defer server.Close()
}
Output:

Types

type Error

type Error struct {
	Response
}

Error represents an error response from the API. Returning it from your handler will produce a message serialized in the following way:

{
	"statusCode": 123,
	"message": "Provided message."
}

Error encapsulates the response which means that all methods available on that type can be used freely on an error.

func NewError

func NewError(statusCode int, message string) Error

NewError creates a new error with the specified status code and message.

func (Error) WithMessage

func (e Error) WithMessage(message string) Error

WithMessage returns a new error with the changed message. This method makes it easy to use the provided builtin error types with non-standard messages.

Example
package main

import (
	"net/http"
	"net/http/httptest"

	"github.com/boreq/rest"
)

func main() {
	handler := func(r *http.Request) rest.RestResponse {
		return rest.ErrInternalServerError.WithMessage("Custom error message.")
	}

	server := httptest.NewServer(rest.Wrap(handler))
	defer server.Close()
}
Output:

type HandlerFunc

type HandlerFunc func(r *http.Request) RestResponse

HandlerFunc returns a rest response instead of accepting a response writer to simplify the flow of control within the handler and replace multiple calls to the response writer with a single return statement.

type Response

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

Response represents a REST API response and implements the RestResponse interface. This is the main type you should be returning from your handlers. Use the Error type instead of using the response directly to return API errors from your handler.

func NewResponse

func NewResponse(body interface{}) Response

NewResponse creates a new response with the provided body and status code http.StatusOK. Body should be a value which can be serialized to JSON, for example a struct.

func (Response) Body

func (r Response) Body() interface{}

Body is a method implementing RestResponse.

func (Response) Header

func (r Response) Header() http.Header

Header is a method implementing RestResponse.

func (Response) StatusCode

func (r Response) StatusCode() int

StatusCode is a method implementing RestResponse.

func (Response) WithHeader

func (r Response) WithHeader(key, value string) Response

WithStatusCode returns a new response with the added response header. Adding the same header multiple times appends the new value instead of replacing it leading to multiple headers with the same name.

func (Response) WithStatusCode

func (r Response) WithStatusCode(statusCode int) Response

WithStatusCode returns a new response with the changed status code.

type RestResponse

type RestResponse interface {
	Header() http.Header
	StatusCode() int
	Body() interface{}
}

RestResponse encapsulates parameters passed to the response writer.

Jump to

Keyboard shortcuts

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