runtime: github.com/go-openapi/runtime/middleware Index | Files | Directories

package middleware

import "github.com/go-openapi/runtime/middleware"

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

Package Files

context.go doc.go go18.go negotiate.go not_implemented.go operation.go parameter.go redoc.go request.go router.go security.go spec.go validation.go

Variables

var Debug = logger.DebugEnabled()

Debug when true turns on verbose logging

var Logger logger.Logger = logger.StandardLogger{}

func NegotiateContentEncoding Uses

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 Uses

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 Uses

func NewOperationExecutor(ctx *Context) http.Handler

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

func NewRouter Uses

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

NewRouter creates a new context aware router middleware

func PassthroughBuilder Uses

func PassthroughBuilder(handler http.Handler) http.Handler

PassthroughBuilder returns the handler, aka the builder identity function

func Redoc Uses

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 Uses

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

SecurityPrincipalFrom request context value.

func SecurityScopesFrom Uses

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

SecurityScopesFrom request context value.

func Serve Uses

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 Uses

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 Uses

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

type Builder Uses

type Builder func(http.Handler) http.Handler

A Builder can create middlewares

type Context Uses

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 Uses

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

NewContext creates a new context wrapper

func NewRoutableContext Uses

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

NewRoutableContext creates a new context for a routable API

func (*Context) APIHandler Uses

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) AllowedMethods Uses

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

AllowedMethods gets the allowed methods for the path of this request

func (*Context) Authorize Uses

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 Uses

func (c *Context) BasePath() string

BasePath returns the base path for this API

func (*Context) BindAndValidate Uses

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 Uses

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 Uses

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 Uses

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

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

func (*Context) NotFound Uses

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 Uses

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

RequiredProduces returns the accepted content types for responses

func (*Context) ResetAuth Uses

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

ResetAuth removes the current principal from the request context

func (*Context) Respond Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func MatchedRouteFrom(req *http.Request) *MatchedRoute

MatchedRouteFrom request context value.

func (*MatchedRoute) HasAuth Uses

func (m *MatchedRoute) HasAuth() bool

HasAuth returns true when the route has a security requirement defined

func (*MatchedRoute) NeedsAuth Uses

func (m *MatchedRoute) NeedsAuth() bool

NeedsAuth returns true when the request still needs to perform authentication

type RedocOpts Uses

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://rebilly.github.io/ReDoc/releases/latest/redoc.min.js
    RedocURL string
    // Title for the documentation site, default to: API documentation
    Title string
}

RedocOpts configures the Redoc middlewares

func (*RedocOpts) EnsureDefaults Uses

func (r *RedocOpts) EnsureDefaults()

EnsureDefaults in case some options are missing

type RequestBinder Uses

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 Uses

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 NotImplemented Uses

func NotImplemented(message string) Responder

NotImplemented the error response when the response is not implemented

type ResponderFunc Uses

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

ResponderFunc wraps a func as a Responder interface

func (ResponderFunc) WriteResponse Uses

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

WriteResponse writes to the response

type RoutableAPI Uses

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 Uses

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 Uses

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 Uses

func (ra *RouteAuthenticator) AllowsAnonymous() bool

func (*RouteAuthenticator) Authenticate Uses

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

Authenticate Authenticator interface implementation

func (*RouteAuthenticator) CommonScopes Uses

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

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

type RouteAuthenticators Uses

type RouteAuthenticators []RouteAuthenticator

RouteAuthenticators represents a group of authenticators that represent a logical OR

func (RouteAuthenticators) AllowsAnonymous Uses

func (ras RouteAuthenticators) AllowsAnonymous() bool

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

func (RouteAuthenticators) Authenticate Uses

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 Uses

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 Uses

type RouteParams []RouteParam

RouteParams the collection of route params

func (RouteParams) Get Uses

func (r RouteParams) Get(name string) string

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

func (RouteParams) GetOK Uses

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 Uses

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

Router represents a swagger aware router

func DefaultRouter Uses

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

DefaultRouter creates a default implemenation of the router

Directories

PathSynopsis
dencoPackage denco provides fast URL router.
headerPackage header provides functions for parsing HTTP headers.
untyped

Package middleware imports 29 packages (graph) and is imported by 412 packages. Updated 2019-09-13. Refresh now. Tools for package owners.