Documentation
¶
Overview ¶
Package api provides a minimal framework for APIs.
There is one main interface and one main function that are used to interact with this package.
API ¶
This interface defines an API, and concrete implementations of an API should be registered with a server, which is returned by;
NewServer ¶
This function takes an API, and returns a `http.Server`.
These two should be used in conjunction to provide a conformant experience across many HTTP APIs.
Example
type MyAPI struct { logger *zap.SugaredLogger } func (a *MyAPI) Endpoints() []api.Endpoint { return []api.Endpoint{ {"GET", "/:id", a.handleGet(), []api.Middleware{}}, } } func (a *MyAPI) handleGet() http.Handler { var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { api.Respond(w, r, http.StatusOK, nil) } return h } func main() { a := MyAPI{logger} srv := api.NewServer(":8080", logger, a) srv.ListenAndServe() }
Index ¶
- func Decode(w http.ResponseWriter, r *http.Request, v interface{}) error
- func Error(w http.ResponseWriter, r *http.Request, err string, code int, ...)
- func LoggerFromRequest(r *http.Request, l *zap.SugaredLogger) *zap.SugaredLogger
- func NewServer(addr string, logger *zap.SugaredLogger, a API, opts ...Option) http.Server
- func NotFound(w http.ResponseWriter, r *http.Request, extras ...ProblemExtra)
- func Problem(w http.ResponseWriter, r *http.Request, title, detail string, code int, ...)
- func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)
- func Respond(w http.ResponseWriter, r *http.Request, code int, data interface{})
- func SetDetails(r *http.Request, path string, params map[string]string) *http.Request
- func URLParam(r *http.Request, name string) string
- type API
- type CorsMiddleware
- type Endpoint
- type Middleware
- type Option
- type ProblemExtra
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Decode ¶
func Decode(w http.ResponseWriter, r *http.Request, v interface{}) error
Decode should be used to convert the request's JSON body into the given v value.
func Error ¶
func Error(w http.ResponseWriter, r *http.Request, err string, code int, extras ...ProblemExtra)
Error replies to the request with the specified error message and HTTP code, using the problem response defined by RFC 7807.
func LoggerFromRequest ¶
func LoggerFromRequest(r *http.Request, l *zap.SugaredLogger) *zap.SugaredLogger
LoggerFromRequest returns a child logger of the given logger with predefined fields. It should be used when logging from within a request handler, so that those logs can be correlated.
func NotFound ¶
func NotFound(w http.ResponseWriter, r *http.Request, extras ...ProblemExtra)
NotFound replies to the request with an HTTP 404 not found error, using the problem response defined by RFC 7807.
func Problem ¶
func Problem(w http.ResponseWriter, r *http.Request, title, detail string, code int, extras ...ProblemExtra)
Problem responds to HTTP request with a response that follows RFC 7807 (https://tools.ietf.org/html/rfc7807). It should be used for error responses.
func Redirect ¶
Redirect replies to the request with a redirect to url. The provided code should be in the 3xx range and is usually http.StatusMovedPermanently, http.StatusFound or http.StatusSeeOther.
func Respond ¶
func Respond(w http.ResponseWriter, r *http.Request, code int, data interface{})
Respond should be used to respond to a http request within a http handler. Respond encodes any data passed in as JSON. Respond also sets the status code of the response on the request details, so middlewares can access this value.
func SetDetails ¶
SetDetails adds the required details into the given request's context. The returned request should then be used.
Types ¶
type API ¶
type API interface { // Endpoints must return all Endpoints of the HTTP API to register with a http router Endpoints() []Endpoint }
API defines a HTTP API that can be exposed using a server
type CorsMiddleware ¶
CorsMiddleware is a function designed to run some code before and/or after another Handler, related to Cross Origin Resource Sharing.
func AllowAllCorsMW ¶
func AllowAllCorsMW() *CorsMiddleware
AllowAllCorsMW returns a cors middleware that adds support for all origins, for all methods, with any header or credential.
func CorsMW ¶
func CorsMW(c *cors.Cors) *CorsMiddleware
CorsMW returns a cors middleware that adds cors support to wrapped handlers, as defined by the given cors options.
func DefaultCorsMW ¶
func DefaultCorsMW() *CorsMiddleware
DefaultCorsMW returns a cors middleware that adds support for all origins for GET and POST methods.
type Endpoint ¶
type Endpoint struct { // The HTTP Method of this endpoint. Method string // The URL Path of this endpoint. Should follow the format for // paths specified by https://github.com/dimfeld/httptreemux. Path string // The handler to invoke when a request for the given Method, Path is received Handler http.Handler // Any endpoint specific middlewares for this handler (i.e. access control) Middlewares []Middleware // Flag to suppress endpoint request/response information log line. SuppressLogs bool // Flag to suppress endpoint appearing in exposed Prometheus metrics. SuppressMetrics bool // The Cross Origin Resource Sharing middleware to add to this endpoint. If // defined, this will also register the 'OPTIONS' method for this endpoint. CorsMiddleware *CorsMiddleware }
Endpoint defines an endpoint of a HTTP API
type Middleware ¶
Middleware is a function designed to run some code before and/or after another Handler. It is designed to remove boilerplate or other concerns not direct to any given Handler.
func LogMW ¶
func LogMW(logger *zap.SugaredLogger) Middleware
LogMW returns a middleware that implements request + response detail logging. The middleware will log upon response.
func MetricsMW ¶
func MetricsMW(reg prometheus.Registerer, endpoints []Endpoint) Middleware
MetricsMW returns a middleware that implements counting + timing of requests using a Prometheus Histogram
type Option ¶
type Option func(*server)
Option is a function that can be passed to NewServer to modify the server.
func WithDefaultMiddleware ¶
func WithDefaultMiddleware(mw []Middleware) Option
WithDefaultMiddleware adds middleware to every endpoint registered with the server.
func WithNotFoundHandler ¶
func WithNotFoundHandler(h func(w http.ResponseWriter, r *http.Request)) Option
WithNotFoundHandler sets the server's not found handler.
func WithPanicHandler ¶
func WithPanicHandler(ph func(w http.ResponseWriter, r *http.Request, err interface{})) Option
WithPanicHandler sets the server's panic handler.
type ProblemExtra ¶
type ProblemExtra func(*problem)
ProblemExtra provides a way to add extra information into the problem response.
func WithDetail ¶
func WithDetail(d string) ProblemExtra
WithDetail allows the detail field to be added to the problem response.
func WithFields ¶
func WithFields(fields map[string]interface{}) ProblemExtra
WithFields allows extra fields to be included in the problem response. Any field keys that clash with those expected in the problem response will not be used.
func WithInstance ¶
func WithInstance(i string) ProblemExtra
WithInstance allows the instance field to be added to the problem response.
func WithType ¶
func WithType(t string) ProblemExtra
WithType allows the type field to be added to the problem response.