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 RapiDoc(opts RapiDocOpts, next 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, opts ...SpecOption) http.Handler
- func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler
- func SwaggerUIOAuth2Callback(opts SwaggerUIOpts, next http.Handler) http.Handler
- type Builder
- type Context
- func (c *Context) APIHandler(builder Builder, opts ...UIOption) http.Handler
- func (c *Context) APIHandlerRapiDoc(builder Builder, opts ...UIOption) http.Handler
- func (c *Context) APIHandlerSwaggerUI(builder Builder, opts ...UIOption) 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
- func (c *Context) SetLogger(lg logger.Logger)
- type DefaultRouterOpt
- type MatchedRoute
- type RapiDocOpts
- type RedocOpts
- type RequestBinder
- type Responder
- type ResponderFunc
- type RoutableAPI
- type RouteAuthenticator
- type RouteAuthenticators
- type RouteParam
- type RouteParams
- type Router
- type SpecOption
- type SwaggerUIOpts
- type UIOption
- 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{}
Logger is the standard libray logger used for printing debug messages
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 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 ¶
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
func Spec ¶
Spec creates a middleware to serve a swagger spec as a JSON document.
This allows for altering the spec before starting the http listener.
The basePath argument indicates the path of the spec document (defaults to "/"). Additional SpecOption can be used to change the name of the document (defaults to "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.
func SwaggerUIOAuth2Callback ¶ added in v0.25.0
func SwaggerUIOAuth2Callback(opts SwaggerUIOpts, next http.Handler) http.Handler
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.
If a nil Router is provided, the DefaultRouter (denco-based) will be used.
func NewRoutableContext ¶
func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context
NewRoutableContext creates a new context for a routable API.
If a nil Router is provided, the DefaultRouter (denco-based) will be used.
func NewRoutableContextWithAnalyzedSpec ¶ added in v0.25.0
func NewRoutableContextWithAnalyzedSpec(spec *loads.Document, an *analysis.Spec, routableAPI RoutableAPI, routes Router) *Context
NewRoutableContextWithAnalyzedSpec is like NewRoutableContext but takes as input an already analysed spec.
If a nil Router is provided, the DefaultRouter (denco-based) will be used.
func (*Context) APIHandler ¶
APIHandler returns a handler to serve the API.
This handler includes a swagger spec, router and the contract defined in the swagger spec.
A spec UI (Redoc) is served at {API base path}/docs and the spec document at /swagger.json (these can be modified with uiOptions).
func (*Context) APIHandlerRapiDoc ¶ added in v0.27.0
APIHandlerRapiDoc returns a handler to serve the API.
This handler includes a swagger spec, router and the contract defined in the swagger spec.
A spec UI (RapiDoc) is served at {API base path}/docs and the spec document at /swagger.json (these can be modified with uiOptions).
func (*Context) APIHandlerSwaggerUI ¶ added in v0.19.20
APIHandlerSwaggerUI returns a handler to serve the API.
This handler includes a swagger spec, router and the contract defined in the swagger spec.
A spec UI (SwaggerUI) is served at {API base path}/docs and the spec document at /swagger.json (these can be modified with uiOptions).
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
func (*Context) RoutesHandler ¶
RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec
type DefaultRouterOpt ¶ added in v0.27.0
type DefaultRouterOpt func(*defaultRouterOpts)
DefaultRouterOpt allows to inject optional behavior to the default router.
func WithDefaultRouterLogger ¶ added in v0.27.0
func WithDefaultRouterLogger(lg logger.Logger) DefaultRouterOpt
WithDefaultRouterLogger sets the debug logger for the default router.
This is enabled only in DEBUG mode.
func WithDefaultRouterLoggerFunc ¶ added in v0.27.0
func WithDefaultRouterLoggerFunc(fn func(string, ...any)) DefaultRouterOpt
WithDefaultRouterLoggerFunc sets a logging debug method for the default router.
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, defaults to: / BasePath string // Path combines with BasePath to construct the path to the UI, defaults to: "docs". Path string // SpecURL is the URL of the spec document. // // Defaults to: /swagger.json SpecURL string // Title for the documentation site, default to: API documentation Title string // Template specifies a custom template to serve the UI Template string // RapiDocURL points to the js asset that generates the rapidoc site. // // Defaults to https://unpkg.com/rapidoc/dist/rapidoc-min.js RapiDocURL string }
RapiDocOpts configures the RapiDoc middlewares
func (*RapiDocOpts) EnsureDefaults ¶ added in v0.19.22
func (r *RapiDocOpts) EnsureDefaults()
type RedocOpts ¶
type RedocOpts struct { // BasePath for the UI, defaults to: / BasePath string // Path combines with BasePath to construct the path to the UI, defaults to: "docs". Path string // SpecURL is the URL of the spec document. // // Defaults to: /swagger.json SpecURL string // Title for the documentation site, default to: API documentation Title string // Template specifies a custom template to serve the UI Template string // RedocURL points to the js that generates the redoc site. // // Defaults to: https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js RedocURL 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, opts ...DefaultRouterOpt) Router
DefaultRouter creates a default implementation of the router
type SpecOption ¶ added in v0.27.0
type SpecOption func(*specOptions)
SpecOption can be applied to the Spec serving middleware
func WithSpecDocument ¶ added in v0.27.0
func WithSpecDocument(doc string) SpecOption
WithSpecDocument sets the name of the JSON document served as a spec.
By default, this is "swagger.json"
func WithSpecPath ¶ added in v0.27.0
func WithSpecPath(pth string) SpecOption
WithSpecPath sets the path to be joined to the base path of the Spec middleware.
This is empty by default.
type SwaggerUIOpts ¶ added in v0.19.20
type SwaggerUIOpts struct { // BasePath for the API, defaults to: / BasePath string // Path combines with BasePath to construct the path to the UI, defaults to: "docs". Path string // SpecURL is the URL of the spec document. // // Defaults to: /swagger.json SpecURL string // Title for the documentation site, default to: API documentation Title string // Template specifies a custom template to serve the UI Template string // OAuthCallbackURL the url called after OAuth2 login OAuthCallbackURL string // SwaggerURL points to the js that generates the SwaggerUI site. // // Defaults to: https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js SwaggerURL string SwaggerPresetURL string SwaggerStylesURL string Favicon32 string Favicon16 string }
SwaggerUIOpts configures the SwaggerUI middleware
func (*SwaggerUIOpts) EnsureDefaults ¶ added in v0.19.20
func (r *SwaggerUIOpts) EnsureDefaults()
EnsureDefaults in case some options are missing
func (*SwaggerUIOpts) EnsureDefaultsOauth2 ¶ added in v0.27.0
func (r *SwaggerUIOpts) EnsureDefaultsOauth2()
type UIOption ¶ added in v0.27.0
type UIOption func(*uiOptions)
UIOption can be applied to UI serving middleware, such as Context.APIHandler or Context.APIHandlerSwaggerUI to alter the defaut behavior.
func WithTemplate ¶ added in v0.27.0
WithTemplate allows to set a custom template for the UI.
UI middleware will panic if the template does not parse or execute properly.
func WithUIBasePath ¶ added in v0.27.0
WithUIBasePath sets the base path from where to serve the UI assets.
By default, Context middleware sets this value to the API base path.
func WithUIPath ¶ added in v0.27.0
WithUIPath sets the path from where to serve the UI assets (i.e. /{basepath}/{path}.
func WithUISpecURL ¶ added in v0.27.0
WithUISpecURL sets the path from where to serve swagger spec document.
This may be specified as a full URL or a path.
By default, this is "/swagger.json"
func WithUITitle ¶ added in v0.27.0
WithUITitle sets the title of the UI.
By default, Context middleware sets this value to the title found in the API spec.
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
func (*UntypedRequestBinder) SetLogger ¶ added in v0.27.0
func (o *UntypedRequestBinder) SetLogger(lg logger.Logger)
SetLogger allows for injecting a logger to catch debug entries.
The logger is enabled in DEBUG mode only.