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 ¶
var ( ErrBadRequest = NewError(http.StatusBadRequest, "Bad request.") 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.") )
Predefined 4xx client errors.
var ( ErrInternalServerError = NewError(http.StatusInternalServerError, "Internal server error.") ErrNotImplemented = NewError(http.StatusNotImplemented, "Not implemented.") ErrBadGateway = NewError(http.StatusBadGateway, "Bad gateway.") 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 (Error) WithMessage ¶
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) StatusCode ¶
StatusCode is a method implementing RestResponse.
func (Response) WithHeader ¶
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 ¶
WithStatusCode returns a new response with the changed status code.
type RestResponse ¶
RestResponse encapsulates parameters passed to the response writer.