api

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2021 License: MIT Imports: 11 Imported by: 3

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

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 added in v0.3.0

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 added in v0.3.2

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 NewServer

func NewServer(addr string, logger *zap.SugaredLogger, a API, opts ...Option) http.Server

NewServer returns a HTTP server for accessing the the given API.

func NotFound added in v0.3.0

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 added in v0.3.0

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 added in v0.2.2

func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)

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 added in v0.3.1

func SetDetails(r *http.Request, path string, params map[string]string) *http.Request

SetDetails adds the required details into the given request's context. The returned request should then be used.

func URLParam

func URLParam(r *http.Request, name string) string

URLParam returns the named parameter from the request's URL path.

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 added in v0.4.0

type CorsMiddleware func(http.Handler) http.Handler

CorsMiddleware is a function designed to run some code before and/or after another Handler, related to Cross Origin Resource Sharing.

func AllowAllCorsMW added in v0.3.3

func AllowAllCorsMW() *CorsMiddleware

AllowAllCorsMW returns a cors middleware that adds support for all origins, for all methods, with any header or credential.

func CorsMW added in v0.4.0

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 added in v0.3.3

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

type Middleware func(http.Handler) http.Handler

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 added in v1.1.0

type Option func(*server)

Option is a function that can be passed to NewServer to modify the server.

func WithDefaultMiddleware added in v1.1.0

func WithDefaultMiddleware(mw []Middleware) Option

WithDefaultMiddleware adds middleware to every endpoint registered with the server.

func WithNotFoundHandler added in v1.1.0

func WithNotFoundHandler(h func(w http.ResponseWriter, r *http.Request)) Option

WithNotFoundHandler sets the server's not found handler.

func WithPanicHandler added in v1.1.0

func WithPanicHandler(ph func(w http.ResponseWriter, r *http.Request, err interface{})) Option

WithPanicHandler sets the server's panic handler.

type ProblemExtra added in v0.3.0

type ProblemExtra func(*problem)

ProblemExtra provides a way to add extra information into the problem response.

func WithDetail added in v0.3.0

func WithDetail(d string) ProblemExtra

WithDetail allows the detail field to be added to the problem response.

func WithFields added in v0.3.0

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 added in v0.3.0

func WithInstance(i string) ProblemExtra

WithInstance allows the instance field to be added to the problem response.

func WithType added in v0.3.0

func WithType(t string) ProblemExtra

WithType allows the type field to be added to the problem response.

Jump to

Keyboard shortcuts

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