Documentation ¶
Overview ¶
Package oas provides utilities to work with OpenAPI 2.0 specification (aka Swagger).
The purpose of this package is to provide utilities for building APIs from the OpenAPI specification in Go idiomatic way on top of `net/http`. The package can handle request validation, request parameters decoding and other routines.
Index ¶
- Variables
- func DecodeQuery(req *http.Request, dst interface{}) error
- func DecodeQueryParams(ps []spec.Parameter, q url.Values, dst interface{}) error
- func DynamicSpecHandler(s *spec.Swagger) http.Handler
- func GetPathParam(req *http.Request, name string) interface{}
- func StaticSpecHandler(s *spec.Swagger) http.Handler
- func WithOperation(req *http.Request, op *Operation) *http.Request
- func WithPathParam(req *http.Request, name string, value interface{}) *http.Request
- type BaseRouter
- type Document
- type JSONError
- type LoadOption
- type LoadOptions
- type LogWriter
- type Middleware
- func BodyValidator(errHandler RequestErrorHandler, opts ...MiddlewareOption) Middleware
- func PathParameterExtractor(extractor func(r *http.Request, key string) string) Middleware
- func QueryValidator(errHandler RequestErrorHandler) Middleware
- func ResponseBodyValidator(errHandler ResponseErrorHandler, opts ...MiddlewareOption) Middleware
- type MiddlewareOption
- type MiddlewareOptions
- type Operation
- type OperationHandlers
- type OperationID
- type RequestErrorHandler
- type ResponseErrorHandler
- type Router
- type RouterOption
- type SpecHandlerType
- type ValidationError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultExtractorFunc = chi.URLParam
DefaultExtractorFunc is the extractor func that should be used with default router.
Functions ¶
func DecodeQuery ¶
DecodeQuery decodes all query params by request operation spec to the dst.
func DecodeQueryParams ¶ added in v0.6.0
DecodeQueryParams decodes query parameters by their spec to the dst.
Example ¶
// In real app parameters will be taken from spec document (yaml or json). params := []spec.Parameter{ *spec.QueryParam("name").Typed("string", ""), *spec.QueryParam("age").Typed("integer", "int32"), *spec.QueryParam("loves_apples").Typed("boolean", ""). AsRequired(). WithDefault(true), } // In real app query will be taken from *http.Request. query := url.Values{"name": []string{"John"}, "age": []string{"27"}} type member struct { Name string `oas:"name"` Age int32 `oas:"age"` LovesApples bool `oas:"loves_apples"` } var m member if err := DecodeQueryParams(params, query, &m); err != nil { panic(err) } fmt.Printf("%#v", m)
Output: oas.member{Name:"John", Age:27, LovesApples:true}
func DynamicSpecHandler ¶ added in v0.5.0
DynamicSpecHandler returns HTTP handler for OpenAPI spec that changes its host and schemes dynamically based on incoming request.
func GetPathParam ¶
GetPathParam returns a path parameter by name from a request. For example, a handler defined on a path "/pet/{id}" gets a request with path "/pet/12" - in this case GetPathParam(req, "id") returns 12.
func StaticSpecHandler ¶ added in v0.5.0
StaticSpecHandler returns HTTP handler for static OpenAPI spec.
func WithOperation ¶ added in v0.2.1
WithOperation returns request with context value defining *spec.Operation.
Types ¶
type BaseRouter ¶
type BaseRouter interface { http.Handler Use(middleware func(http.Handler) http.Handler) Route(method string, pathPattern string, handler http.Handler) }
BaseRouter is an underlying router used in oas router. Any third-party router can be a BaseRouter by using adapter pattern.
func ChiAdapter ¶
func ChiAdapter(router chi.Router) BaseRouter
ChiAdapter returns a BaseRouter made from chi router (github.com/go-chi/chi). This is just an example adapter implementation, you should implement your own adapter for a desired router if you need it.
func DefaultBaseRouter ¶ added in v0.7.0
func DefaultBaseRouter() BaseRouter
DefaultBaseRouter is the base router used by default when no specific base router passed to NewRouter().
type JSONError ¶ added in v0.5.0
type JSONError struct {
// contains filtered or unexported fields
}
JSONError occurs on json encoding or decoding. It can happen both in request and response validation.
type LoadOption ¶ added in v0.6.0
type LoadOption func(*LoadOptions)
LoadOption is option to use when loading specification.
func LoadCacheDir ¶ added in v0.6.0
func LoadCacheDir(dir string) LoadOption
LoadCacheDir returns option that allows to load expanded spec from cache.
func LoadSetAPIVersion ¶ added in v0.6.0
func LoadSetAPIVersion(version string) LoadOption
LoadSetAPIVersion returns option that sets application API version.
func LoadSetHost ¶ added in v0.6.0
func LoadSetHost(host string) LoadOption
LoadSetHost returns option that sets specification host.
func LoadSetSchemes ¶ added in v0.6.0
func LoadSetSchemes(schemes []string) LoadOption
LoadSetSchemes returns option that sets specification schemes.
type LoadOptions ¶ added in v0.6.0
type LoadOptions struct {
// contains filtered or unexported fields
}
LoadOptions represent options that are used on specification load.
type LogWriter ¶
type LogWriter func(format string, args ...interface{})
LogWriter logs router operations that will be handled and what will be not during router creation. Useful for debugging.
type Middleware ¶
Middleware describes a middleware that can be applied to a http.handler.
func BodyValidator ¶ added in v0.4.0
func BodyValidator(errHandler RequestErrorHandler, opts ...MiddlewareOption) Middleware
BodyValidator returns new Middleware that validates request body against parameters defined in OpenAPI 2.0 spec.
func PathParameterExtractor ¶ added in v0.4.0
func PathParameterExtractor(extractor func(r *http.Request, key string) string) Middleware
PathParameterExtractor returns new Middleware that extracts parameters defined in OpenAPI 2.0 spec as path parameters from path.
func QueryValidator ¶ added in v0.4.0
func QueryValidator(errHandler RequestErrorHandler) Middleware
QueryValidator returns new Middleware that validates request query parameters against OpenAPI 2.0 spec.
func ResponseBodyValidator ¶ added in v0.4.0
func ResponseBodyValidator(errHandler ResponseErrorHandler, opts ...MiddlewareOption) Middleware
ResponseBodyValidator returns new Middleware that validates response body against schema defined in OpenAPI 2.0 spec.
type MiddlewareOption ¶ added in v0.6.0
type MiddlewareOption func(*MiddlewareOptions)
MiddlewareOption represent option for middleware.
func ContentTypeRegexSelector ¶ added in v0.6.0
func ContentTypeRegexSelector(selector *regexp.Regexp) MiddlewareOption
ContentTypeRegexSelector select requests/responses based on Content-Type header. If any selector matches Content-Type of the request/response, then it will be validated. Otherwise, validator skips validation of the request/response.
This options can be applied to the following middlewares: - BodyValidator - ResponseBodyValidator
type MiddlewareOptions ¶ added in v0.6.0
type MiddlewareOptions struct {
// contains filtered or unexported fields
}
MiddlewareOptions represent options for middleware.
type Operation ¶ added in v0.7.0
Operation describes a single API operation on a path.
func GetOperation ¶
GetOperation returns *spec.Operation from the request's context. In case of operation not found GetOperation returns nil.
func MustOperation ¶ added in v0.1.2
MustOperation returns *spec.Operation from the request's context. In case of operation not found MustOperation panics.
type OperationHandlers ¶
type OperationHandlers map[OperationID]http.Handler
OperationHandlers maps OperationID to its handler.
type OperationID ¶
type OperationID string
OperationID is an operation identifier.
func (OperationID) String ¶
func (oid OperationID) String() string
String implements fmt.Stringer interface.
Example ¶
opID := OperationID("addPet") fmt.Fprint(os.Stdout, opID.String())
Output: addPet
type RequestErrorHandler ¶
RequestErrorHandler is a function that handles an error occurred in middleware while working with request. It is the library user responsibility to implement this to handle various errors that can occur during middleware work. This errors can include request validation errors, json encoding errors and other. Also, user must return proper boolean value that indicates if the request should continue or it should be stopped (basically, call "next" or not).
type ResponseErrorHandler ¶
type ResponseErrorHandler func(w http.ResponseWriter, req *http.Request, err error)
ResponseErrorHandler is a function that handles an error occurred in middleware while working with response. It is the library user responsibility to implement this to handle various errors that can occur on middleware work. This errors can include response validation errors, json serialization errors and others.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router routes requests based on OAS 2.0 spec operations.
func NewRouter ¶
func NewRouter( doc *Document, handlers OperationHandlers, options ...RouterOption, ) (*Router, error)
NewRouter returns a new Router.
type RouterOption ¶
type RouterOption func(*Router)
RouterOption is an option for oas router.
func Base ¶
func Base(br BaseRouter) RouterOption
Base returns an option that sets a BaseRouter for oa2 router. It allows to plug-in your favorite router to the oas router.
func DebugLog ¶
func DebugLog(lw LogWriter) RouterOption
DebugLog returns an option that sets a debug log for oas router. Debug log may help to see what router operations will be handled and what will be not.
func ServeSpec ¶ added in v0.5.0
func ServeSpec(t SpecHandlerType) RouterOption
ServeSpec returns an option that makes router serve its spec.
func Use ¶
func Use(mw Middleware) RouterOption
Use returns an option that sets a middleware for router operations.
This middleware is applied to each operation handler. Thus, this middleware can use request context to extract and use operation spec. Also, this middleware cannot affect routing; for example, CORS middleware that handles OPTIONS method for all routes won't work with Use; use Wrap option instead.
Multiple middlewares will be executed exactly in the same order they were passed to the router. For example:
router, _ := oas.NewRouter( doc, handlers, oas.Use(RequestID), oas.Use(RequestLogger), )
Here the RequestLogger will be executed after RequestID and thus will be able to use request id that RequestID middleware stored in a request context.
func Wrap ¶ added in v0.7.0
func Wrap(mw Middleware) RouterOption
Wrap returns an option that sets a middleware for the router.
This middleware is applied to the router itself. Thus, this middleware cannot extract operation spec from context. But, in contrast to Use, this middleware can affect routing, so this is a proper option to use CORS and similar.
All oas-specific middlewares like oas.QueryValidator should use Use option instead.
Multiple middlewares will be executed exactly in the same order they were passed to the router. For example:
router, _ := oas.NewRouter( doc, handlers, oas.Wrap(RequestID), oas.Wrap(RequestLogger), )
Here the RequestLogger will be executed after RequestID and thus will be able to use request id that RequestID middleware stored in a request context.
type SpecHandlerType ¶ added in v0.5.0
type SpecHandlerType int
SpecHandlerType represents spec handler type.
const ( // SpecHandlerTypeDynamic represents dynamic spec handler. SpecHandlerTypeDynamic SpecHandlerType = iota + 1 // SpecHandlerTypeStatic represents static spec handler. SpecHandlerTypeStatic )
type ValidationError ¶
type ValidationError struct {
// contains filtered or unexported fields
}
ValidationError occurs on request or response validation.
func (ValidationError) Errors ¶
func (ve ValidationError) Errors() []error
Errors returns validation errors.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
cmd
|
|
oas-expand
CLI utility that expands OAS file to reduce init time.
|
CLI utility that expands OAS file to reduce init time. |
e2e
|
|
Package validate provides utilities that allow to validate request and response data against OpenAPI Specification parameter and schema definitions.
|
Package validate provides utilities that allow to validate request and response data against OpenAPI Specification parameter and schema definitions. |