middleware

package
v0.24.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2022 License: Apache-2.0 Imports: 29 Imported by: 4,487

Documentation

Overview

Package middleware provides the library with helper functions for serving swagger APIs.

Pseudo middleware handler

import (
	"net/http"

	"github.com/go-openapi/errors"
)

func newCompleteMiddleware(ctx *Context) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		// use context to lookup routes
		if matched, ok := ctx.RouteInfo(r); ok {

			if matched.NeedsAuth() {
				if _, err := ctx.Authorize(r, matched); err != nil {
					ctx.Respond(rw, r, matched.Produces, matched, err)
					return
				}
			}

			bound, validation := ctx.BindAndValidate(r, matched)
			if validation != nil {
				ctx.Respond(rw, r, matched.Produces, matched, validation)
				return
			}

			result, err := matched.Handler.Handle(bound)
			if err != nil {
				ctx.Respond(rw, r, matched.Produces, matched, err)
				return
			}

			ctx.Respond(rw, r, matched.Produces, matched, result)
			return
		}

		// Not found, check if it exists in the other methods first
		if others := ctx.AllowedMethods(r); len(others) > 0 {
			ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others))
			return
		}
		ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path))
	})
}

Index

Constants

This section is empty.

Variables

Debug when true turns on verbose logging

Functions

func NegotiateContentEncoding

func NegotiateContentEncoding(r *http.Request, offers []string) string

NegotiateContentEncoding returns the best offered content encoding for the request's Accept-Encoding header. If two offers match with equal weight and then the offer earlier in the list is preferred. If no offers are acceptable, then "" is returned.

func NegotiateContentType

func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string

NegotiateContentType returns the best offered content type for the request's Accept header. If two offers match with equal weight, then the more specific offer is preferred. For example, text/* trumps */*. If two offers match with equal weight and specificity, then the offer earlier in the list is preferred. If no offers match, then defaultOffer is returned.

func NewOperationExecutor

func NewOperationExecutor(ctx *Context) http.Handler

NewOperationExecutor creates a context aware middleware that handles the operations after routing

func NewRouter

func NewRouter(ctx *Context, next http.Handler) http.Handler

NewRouter creates a new context aware router middleware

func PassthroughBuilder

func PassthroughBuilder(handler http.Handler) http.Handler

PassthroughBuilder returns the handler, aka the builder identity function

func RapiDoc added in v0.19.22

func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler

RapiDoc creates a middleware to serve a documentation site for a swagger spec. This allows for altering the spec before starting the http listener.

func Redoc

func Redoc(opts RedocOpts, next http.Handler) http.Handler

Redoc creates a middleware to serve a documentation site for a swagger spec. This allows for altering the spec before starting the http listener.

func SecurityPrincipalFrom

func SecurityPrincipalFrom(req *http.Request) interface{}

SecurityPrincipalFrom request context value.

func SecurityScopesFrom

func SecurityScopesFrom(req *http.Request) []string

SecurityScopesFrom request context value.

func Serve

func Serve(spec *loads.Document, api *untyped.API) http.Handler

Serve serves the specified spec with the specified api registrations as a http.Handler

func ServeWithBuilder

func ServeWithBuilder(spec *loads.Document, api *untyped.API, builder Builder) http.Handler

ServeWithBuilder serves the specified spec with the specified api registrations as a http.Handler that is decorated by the Builder

func Spec

func Spec(basePath string, b []byte, next http.Handler) http.Handler

Spec creates a middleware to serve a swagger spec. This allows for altering the spec before starting the http listener. This can be useful if you want to serve the swagger spec from another path than /swagger.json

func SwaggerUI added in v0.19.20

func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler

SwaggerUI creates a middleware to serve a documentation site for a swagger spec. This allows for altering the spec before starting the http listener.

Types

type Builder

type Builder func(http.Handler) http.Handler

A Builder can create middlewares

type Context

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

Context is a type safe wrapper around an untyped request context used throughout to store request context with the standard context attached to the http.Request

func NewContext

func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context

NewContext creates a new context wrapper

func NewRoutableContext

func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context

NewRoutableContext creates a new context for a routable API

func (*Context) APIHandler

func (c *Context) APIHandler(builder Builder) http.Handler

APIHandler returns a handler to serve the API, this includes a swagger spec, router and the contract defined in the swagger spec

func (*Context) APIHandlerSwaggerUI added in v0.19.20

func (c *Context) APIHandlerSwaggerUI(builder Builder) http.Handler

func (*Context) AllowedMethods

func (c *Context) AllowedMethods(request *http.Request) []string

AllowedMethods gets the allowed methods for the path of this request

func (*Context) Authorize

func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interface{}, *http.Request, error)

Authorize authorizes the request Returns the principal object and a shallow copy of the request when its context doesn't contain the principal, otherwise the same request or an error (the last) if one of the authenticators returns one or an Unauthenticated error

func (*Context) BasePath

func (c *Context) BasePath() string

BasePath returns the base path for this API

func (*Context) BindAndValidate

func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (interface{}, *http.Request, error)

BindAndValidate binds and validates the request Returns the validation map and a shallow copy of the request when its context doesn't contain the validation, otherwise it returns the same request or an CompositeValidationError error

func (*Context) BindValidRequest

func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, binder RequestBinder) error

BindValidRequest binds a params object to a request but only when the request is valid if the request is not valid an error will be returned

func (*Context) ContentType

func (c *Context) ContentType(request *http.Request) (string, string, *http.Request, error)

ContentType gets the parsed value of a content type Returns the media type, its charset and a shallow copy of the request when its context doesn't contain the content type value, otherwise it returns the same request Returns the error that runtime.ContentType may retunrs.

func (*Context) LookupRoute

func (c *Context) LookupRoute(request *http.Request) (*MatchedRoute, bool)

LookupRoute looks a route up and returns true when it is found

func (*Context) NotFound

func (c *Context) NotFound(rw http.ResponseWriter, r *http.Request)

NotFound the default not found responder for when no route has been matched yet

func (*Context) RequiredProduces

func (c *Context) RequiredProduces() []string

RequiredProduces returns the accepted content types for responses

func (*Context) ResetAuth

func (c *Context) ResetAuth(request *http.Request) *http.Request

ResetAuth removes the current principal from the request context

func (*Context) Respond

func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data interface{})

Respond renders the response after doing some content negotiation

func (*Context) ResponseFormat

func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *http.Request)

ResponseFormat negotiates the response content type Returns the response format and a shallow copy of the request if its context doesn't contain the response format, otherwise the same request

func (*Context) RouteInfo

func (c *Context) RouteInfo(request *http.Request) (*MatchedRoute, *http.Request, bool)

RouteInfo tries to match a route for this request Returns the matched route, a shallow copy of the request if its context contains the matched router, otherwise the same request, and a bool to indicate if it the request matches one of the routes, if it doesn't then it returns false and nil for the other two return values

func (*Context) RoutesHandler

func (c *Context) RoutesHandler(builder Builder) http.Handler

RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec

type MatchedRoute

type MatchedRoute struct {
	Params        RouteParams
	Consumer      runtime.Consumer
	Producer      runtime.Producer
	Authenticator *RouteAuthenticator
	// contains filtered or unexported fields
}

MatchedRoute represents the route that was matched in this request

func MatchedRouteFrom

func MatchedRouteFrom(req *http.Request) *MatchedRoute

MatchedRouteFrom request context value.

func (*MatchedRoute) HasAuth

func (m *MatchedRoute) HasAuth() bool

HasAuth returns true when the route has a security requirement defined

func (*MatchedRoute) NeedsAuth

func (m *MatchedRoute) NeedsAuth() bool

NeedsAuth returns true when the request still needs to perform authentication

type RapiDocOpts added in v0.19.22

type RapiDocOpts struct {
	// BasePath for the UI path, defaults to: /
	BasePath string
	// Path combines with BasePath for the full UI path, defaults to: docs
	Path string
	// SpecURL the url to find the spec for
	SpecURL string
	// RapiDocURL for the js that generates the rapidoc site, defaults to: https://cdn.jsdelivr.net/npm/rapidoc/bundles/rapidoc.standalone.js
	RapiDocURL string
	// Title for the documentation site, default to: API documentation
	Title string
}

RapiDocOpts configures the RapiDoc middlewares

func (*RapiDocOpts) EnsureDefaults added in v0.19.22

func (r *RapiDocOpts) EnsureDefaults()

EnsureDefaults in case some options are missing

type RedocOpts

type RedocOpts struct {
	// BasePath for the UI path, defaults to: /
	BasePath string
	// Path combines with BasePath for the full UI path, defaults to: docs
	Path string
	// SpecURL the url to find the spec for
	SpecURL string
	// RedocURL for the js that generates the redoc site, defaults to: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js
	RedocURL string
	// Title for the documentation site, default to: API documentation
	Title string
}

RedocOpts configures the Redoc middlewares

func (*RedocOpts) EnsureDefaults

func (r *RedocOpts) EnsureDefaults()

EnsureDefaults in case some options are missing

type RequestBinder

type RequestBinder interface {
	BindRequest(*http.Request, *MatchedRoute) error
}

RequestBinder is an interface for types to implement when they want to be able to bind from a request

type Responder

type Responder interface {
	WriteResponse(http.ResponseWriter, runtime.Producer)
}

Responder is an interface for types to implement when they want to be considered for writing HTTP responses

func Error

func Error(code int, data interface{}, headers ...http.Header) Responder

Error creates a generic responder for returning errors, the data will be serialized with the matching producer for the request

func NotImplemented

func NotImplemented(message string) Responder

NotImplemented the error response when the response is not implemented

type ResponderFunc

type ResponderFunc func(http.ResponseWriter, runtime.Producer)

ResponderFunc wraps a func as a Responder interface

func (ResponderFunc) WriteResponse

func (fn ResponderFunc) WriteResponse(rw http.ResponseWriter, pr runtime.Producer)

WriteResponse writes to the response

type RoutableAPI

type RoutableAPI interface {
	HandlerFor(string, string) (http.Handler, bool)
	ServeErrorFor(string) func(http.ResponseWriter, *http.Request, error)
	ConsumersFor([]string) map[string]runtime.Consumer
	ProducersFor([]string) map[string]runtime.Producer
	AuthenticatorsFor(map[string]spec.SecurityScheme) map[string]runtime.Authenticator
	Authorizer() runtime.Authorizer
	Formats() strfmt.Registry
	DefaultProduces() string
	DefaultConsumes() string
}

RoutableAPI represents an interface for things that can serve as a provider of implementations for the swagger router

type RouteAuthenticator

type RouteAuthenticator struct {
	Authenticator map[string]runtime.Authenticator
	Schemes       []string
	Scopes        map[string][]string
	// contains filtered or unexported fields
}

RouteAuthenticator is an authenticator that can compose several authenticators together. It also knows when it contains an authenticator that allows for anonymous pass through. Contains a group of 1 or more authenticators that have a logical AND relationship

func (*RouteAuthenticator) AllScopes

func (ra *RouteAuthenticator) AllScopes() []string

AllScopes returns a list of unique scopes that is the combination of all the scopes in the requirements

func (*RouteAuthenticator) AllowsAnonymous

func (ra *RouteAuthenticator) AllowsAnonymous() bool

func (*RouteAuthenticator) Authenticate

func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error)

Authenticate Authenticator interface implementation

func (*RouteAuthenticator) CommonScopes

func (ra *RouteAuthenticator) CommonScopes() []string

CommonScopes returns a list of unique scopes that are common in all the scopes in the requirements

type RouteAuthenticators

type RouteAuthenticators []RouteAuthenticator

RouteAuthenticators represents a group of authenticators that represent a logical OR

func (RouteAuthenticators) AllowsAnonymous

func (ras RouteAuthenticators) AllowsAnonymous() bool

AllowsAnonymous returns true when there is an authenticator that means optional auth

func (RouteAuthenticators) Authenticate

func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error)

Authenticate method implemention so this collection can be used as authenticator

type RouteParam

type RouteParam struct {
	Name  string
	Value string
}

RouteParam is a object to capture route params in a framework agnostic way. implementations of the muxer should use these route params to communicate with the swagger framework

type RouteParams

type RouteParams []RouteParam

RouteParams the collection of route params

func (RouteParams) Get

func (r RouteParams) Get(name string) string

Get gets the value for the route param for the specified key

func (RouteParams) GetOK

func (r RouteParams) GetOK(name string) ([]string, bool, bool)

GetOK gets the value but also returns booleans to indicate if a key or value is present. This aids in validation and satisfies an interface in use there

The returned values are: data, has key, has value

type Router

type Router interface {
	Lookup(method, path string) (*MatchedRoute, bool)
	OtherMethods(method, path string) []string
}

Router represents a swagger aware router

func DefaultRouter

func DefaultRouter(spec *loads.Document, api RoutableAPI) Router

DefaultRouter creates a default implemenation of the router

type SwaggerUIOpts added in v0.19.20

type SwaggerUIOpts struct {
	// BasePath for the UI path, defaults to: /
	BasePath string
	// Path combines with BasePath for the full UI path, defaults to: docs
	Path string
	// SpecURL the url to find the spec for
	SpecURL string

	// The three components needed to embed swagger-ui
	SwaggerURL       string
	SwaggerPresetURL string
	SwaggerStylesURL string

	Favicon32 string
	Favicon16 string

	// Title for the documentation site, default to: API documentation
	Title string
}

SwaggerUIOpts configures the Swaggerui middlewares

func (*SwaggerUIOpts) EnsureDefaults added in v0.19.20

func (r *SwaggerUIOpts) EnsureDefaults()

EnsureDefaults in case some options are missing

type UntypedRequestBinder

type UntypedRequestBinder struct {
	Spec       *spec.Swagger
	Parameters map[string]spec.Parameter
	Formats    strfmt.Registry
	// contains filtered or unexported fields
}

UntypedRequestBinder binds and validates the data from a http request

func NewUntypedRequestBinder

func NewUntypedRequestBinder(parameters map[string]spec.Parameter, spec *spec.Swagger, formats strfmt.Registry) *UntypedRequestBinder

NewUntypedRequestBinder creates a new binder for reading a request.

func (*UntypedRequestBinder) Bind

func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data interface{}) error

Bind perform the databinding and validation

Directories

Path Synopsis
Package denco provides fast URL router.
Package denco provides fast URL router.
Package header provides functions for parsing HTTP headers.
Package header provides functions for parsing HTTP headers.

Jump to

Keyboard shortcuts

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