Documentation ¶
Overview ¶
Package jsonrest implements a microframework for writing RESTful web applications.
Endpoints are defined as:
func(ctx context.Context, req *jsonrest.Request) (interface{}, error)
If an endpoint returns a value along with a nil error, the value will be rendered to the client as JSON with status code 200. You can also return a Response object if you need another type of success code (e.g. 204).
If an error is returned, it will be sanitized and returned to the client as json. Errors generated by a call to `jsonrest.Error(status, code, message)` will be rendered as-is to the client, along with the given HTTP status code. Any other errors will be obfuscated to the caller (unless `router.DumpError` is enabled).
Example
func main() { r := jsonrest.NewRouter() r.Use(logging) r.Get("/", hello) } func hello(ctx context.Context, req *jsonrest.Reqeust) (interface{}, error) { return jsonrest.M{"message": "Hello, world"}, nil } func logging(next jsonrest.Endpoint) jsonrest.Endpoint { return func(ctx context.Context, req *jsonrest.Request) (interface{}, error) { start := time.Now() defer func() { log.Printf("%s (%v)\n", req.URL().Path, time.Since(start)) }() return next(ctx, req) } }
Index ¶
- Constants
- type Endpoint
- type HTTPError
- type HTTPErrorResponse
- type M
- type Middleware
- type Option
- type Request
- func (r *Request) BasicAuth() (username, password string, ok bool)
- func (r *Request) BindBody(val interface{}) error
- func (r *Request) FormFile(name string, maxMultipartMemory int64) (multipart.File, *multipart.FileHeader, error)
- func (r *Request) Get(key interface{}) interface{}
- func (r *Request) Header(name string) string
- func (r *Request) Method() string
- func (r *Request) Param(name string) string
- func (r *Request) Query(name string) string
- func (r *Request) Raw() *http.Request
- func (r *Request) Route() string
- func (r *Request) Set(key, val interface{})
- func (r *Request) SetResponseHeader(key, val string)
- func (r *Request) URL() *url.URL
- type Response
- type RouteMap
- type Router
- func (r *Router) Get(path string, endpoint Endpoint)
- func (r *Router) Group(groupOptions ...Option) *Router
- func (r *Router) Handle(method, path string, endpoint Endpoint)
- func (r *Router) Head(path string, endpoint Endpoint)
- func (r *Router) Post(path string, endpoint Endpoint)
- func (r *Router) Routes(m RouteMap)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Use(ms ...Middleware)
Constants ¶
const ( HeaderAcceptEncoding = "Accept-Encoding" GzipEncoding = "gzip" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type HTTPError ¶
type HTTPError struct { Code string Message string Details []string Status int // contains filtered or unexported fields }
HTTPError is an error that will be rendered to the client.
func BadRequest ¶
BadRequest returns an HTTP 400 Bad Request error with a custom error message.
func Unauthorized ¶
Unauthorized returns an HTTP 401 Unauthorized error with a custom error message.
func UnprocessableEntity ¶
UnprocessableEntity returns an HTTP 422 UnprocessableEntity error with a custom error message.
func (*HTTPError) Cause ¶
Cause returns the wrapped error, if any. For compatibility with github.com/pkg/errors.
func (*HTTPError) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (*HTTPError) StatusCode ¶
StatusCode implements the HTTPErrorResponse interface.
type HTTPErrorResponse ¶
HTTPErrorResponse allows to customize the format of non-200 http responses. If the handler returns an error which implements this interface, it will be marshaled as-is to the response and written with the specified status code.
type M ¶
type M map[string]interface{}
M is a shorthand for map[string]interface{}. Responses from the server may be of this type.
type Middleware ¶
Middleware is a function that wraps an endpoint to add new behaviour.
For example, you might create a logging middleware that looks like:
func LoggingMiddleware(logger *logger.Logger) Middleware { return func(next jsonrest.Endpoint) jsonrest.Endpoint { return func(ctx context.Context, req *jsonrest.Request) (interface{}, error) { start := time.Now() defer func() { log.Printf("%s (%v)", req.URL.Path, time.Since(start)) }() return next(ctx, req) } } }
type Option ¶
type Option func(*Router)
func WithCompressionEnabled ¶
WithCompressionEnabled is an Option available for NewRouter to configure gzip compression. The compression level can be gzip.DefaultCompression, gzip.NoCompression, gzip.HuffmanOnly or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive.
func WithDisableJSONIndent ¶
func WithDisableJSONIndent() Option
WithDisableJSONIndent is an Option available for NewRouter to configure JSON responses without indenting
func WithNotFoundHandler ¶
WithNotFoundHandler is an Option available for NewRouter to configure the not found handler.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
A Request represents a RESTful HTTP request received by the server.
func NewTestRequest ¶
NewTestRequest allows construction of a Request object with its internal members populated. This can be used to accomplish unit testing on endpoint handlers. This should only be used in test code.
func (*Request) BasicAuth ¶
BasicAuth returns the username and password, if the request uses HTTP Basic Authentication.
func (*Request) FormFile ¶
func (r *Request) FormFile(name string, maxMultipartMemory int64) (multipart.File, *multipart.FileHeader, error)
FormFile returns the first file for the provided form key.
func (*Request) Get ¶
func (r *Request) Get(key interface{}) interface{}
Get returns the meta value for the key.
func (*Request) Set ¶
func (r *Request) Set(key, val interface{})
Set sets a meta value for the key.
func (*Request) SetResponseHeader ¶
SetResponseHeader sets a response header.
type Response ¶
type Response struct { Body interface{} StatusCode int }
Response is a type that can be returned by the endpoint for setting a custom HTTP success status code with the response body.
type RouteMap ¶
RouteMap is a map of a method-path pair to an endpoint. For example:
jsonrest.RouteMap{ "GET /ping": pingEndpoint, "HEAD /api/check": checkEndpoint, "POST /api/update": updateEndpoint, "PUT /api/update": updateEndpoint, }
type Router ¶
type Router struct { // DumpErrors indicates if internal errors should be displayed in the // response; useful for local debugging. DumpErrors bool // contains filtered or unexported fields }
A Router is an http.Handler that routes incoming requests to registered endpoints.
func (*Router) Group ¶
Group creates a new subrouter, representing a group of routes, from the given Router. This subrouter may have its own middleware, but will also inherit its parent's middleware. It will also inherit all the parent options which can be overridden by passing new options.
func (*Router) Routes ¶
Routes registers all routes in the route map. It x panic if an entry is malformed.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements the http.Handler interface.
func (*Router) Use ¶
func (r *Router) Use(ms ...Middleware)
Use registers a middleware to be used for all routes.