Documentation
¶
Overview ¶
Package openapi provides OpenAPI 3.x request and response validation middleware for relay HTTP clients using github.com/getkin/kin-openapi.
When attached, each request is validated against the spec before it is sent. If validation fails the request is aborted and a structured ValidationError is returned without making a network call. Optionally, responses can also be validated after they are received.
Usage ¶
import (
"github.com/jhonsferg/relay"
relayopenapi "github.com/jhonsferg/relay/ext/openapi"
)
// Load the OpenAPI spec.
doc, err := relayopenapi.LoadFile("openapi.yaml")
if err != nil { log.Fatal(err) }
client := relay.New(
relay.WithBaseURL("https://api.example.com"),
relayopenapi.WithValidation(doc),
)
// Responses can also be validated:
client = relay.New(
relay.WithBaseURL("https://api.example.com"),
relayopenapi.WithValidation(doc, relayopenapi.WithResponseValidation()),
)
Strict mode ¶
By default unknown query parameters and headers are allowed. Enable strict mode to reject them:
relayopenapi.WithValidation(doc, relayopenapi.WithStrict())
Error handling ¶
A validation failure returns a *ValidationError that implements error. Use errors.As to access the underlying kin-openapi details.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WithValidation ¶
WithValidation returns a relay.Option that installs an OpenAPI validation transport middleware. Requests that do not conform to doc are rejected before reaching the network. Pass WithResponseValidation to also validate responses.
Types ¶
type Option ¶
type Option func(*option)
Option configures WithValidation.
func WithResponseValidation ¶
func WithResponseValidation() Option
WithResponseValidation enables validation of HTTP responses in addition to requests.
func WithStrict ¶
func WithStrict() Option
WithStrict rejects requests that contain query parameters or headers not described in the spec.
type ValidationError ¶
type ValidationError struct {
// Phase indicates whether the failure was on "request" or "response".
Phase string
// Cause is the underlying kin-openapi validation error.
Cause error
}
ValidationError is returned when a request or response does not conform to the OpenAPI specification.
func IsValidationError ¶
func IsValidationError(err error) (*ValidationError, bool)
IsValidationError reports whether err is (or wraps) a *ValidationError.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error