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 ¶
- Variables
- func NegotiateContentEncoding(r *http.Request, offers []string) string
- func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string
- func NewOperationExecutor(ctx *Context) http.Handler
- func NewRouter(ctx *Context, next http.Handler) http.Handler
- func PassthroughBuilder(handler http.Handler) http.Handler
- func Redoc(opts RedocOpts, next http.Handler) http.Handler
- func SecurityPrincipalFrom(req *http.Request) interface{}
- func SecurityScopesFrom(req *http.Request) []string
- func Serve(spec *loads.Document, api *untyped.API) http.Handler
- func ServeWithBuilder(spec *loads.Document, api *untyped.API, builder Builder) http.Handler
- func Spec(basePath string, b []byte, next http.Handler) http.Handler
- type Builder
- type Context
- func (c *Context) APIHandler(builder Builder) http.Handler
- func (c *Context) AllowedMethods(request *http.Request) []string
- func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interface{}, *http.Request, error)
- func (c *Context) BasePath() string
- func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (interface{}, *http.Request, error)
- func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, binder RequestBinder) error
- func (c *Context) ContentType(request *http.Request) (string, string, *http.Request, error)
- func (c *Context) LookupRoute(request *http.Request) (*MatchedRoute, bool)
- func (c *Context) NotFound(rw http.ResponseWriter, r *http.Request)
- func (c *Context) RequiredProduces() []string
- func (c *Context) ResetAuth(request *http.Request) *http.Request
- func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, ...)
- func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *http.Request)
- func (c *Context) RouteInfo(request *http.Request) (*MatchedRoute, *http.Request, bool)
- func (c *Context) RoutesHandler(builder Builder) http.Handler
- type MatchedRoute
- type RedocOpts
- type RequestBinder
- type Responder
- type ResponderFunc
- type RoutableAPI
- type RouteAuthenticator
- type RouteAuthenticators
- type RouteParam
- type RouteParams
- type Router
- type UntypedRequestBinder
Constants ¶
This section is empty.
Variables ¶
var Debug = logger.DebugEnabled()
Debug when true turns on verbose logging
var Logger logger.Logger = logger.StandardLogger{}
Functions ¶
func NegotiateContentEncoding ¶
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 ¶
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 ¶
NewOperationExecutor creates a context aware middleware that handles the operations after routing
func PassthroughBuilder ¶
PassthroughBuilder returns the handler, aka the builder identity function
func Redoc ¶
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 ¶
SecurityPrincipalFrom request context value.
func SecurityScopesFrom ¶
SecurityScopesFrom request context value.
func ServeWithBuilder ¶
ServeWithBuilder serves the specified spec with the specified api registrations as a http.Handler that is decorated by the Builder
Types ¶
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 ¶
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 ¶
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 ¶
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) 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 ¶
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 ¶
RequiredProduces returns the accepted content types for responses
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 ¶
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 ¶
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
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 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 ¶
Error creates a generic responder for returning errors, the data will be serialized with the matching producer for the request
func NotImplemented ¶
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 ¶
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
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 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