validator

package
v0.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2024 License: MPL-2.0 Imports: 33 Imported by: 0

Documentation

Overview

Example (ValidateMultipartFormData)
const spec = `
openapi: 3.0.0
info:
  title: 'Validator'
  version: 0.0.1
paths:
  /test:
    post:
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - file
              properties:
                file:
                  type: string
                  format: binary
                categories:
                  type: array
                  items:
                    $ref: "#/components/schemas/Category"
      responses:
        '200':
          description: Created

components:
  schemas:
    Category:
      type: object
      properties:
        name:
          type: string
      required:
        - name
`

loader := openapi3.NewLoader()
doc, err := loader.LoadFromData([]byte(spec))
if err != nil {
	panic(err)
}
if err = doc.Validate(loader.Context); err != nil {
	panic(err)
}

router, err := gorillamux.NewRouter(doc)
if err != nil {
	panic(err)
}

body := &bytes.Buffer{}
writer := multipart.NewWriter(body)

{ // Add a single "categories" item as part data
	h := make(textproto.MIMEHeader)
	h.Set("Content-Disposition", `form-data; name="categories"`)
	h.Set("Content-Type", "application/json")
	fw, err := writer.CreatePart(h)
	if err != nil {
		panic(err)
	}
	if _, err = io.Copy(fw, strings.NewReader(`{"name": "foo"}`)); err != nil {
		panic(err)
	}
}

{ // Add a single "categories" item as part data, again
	h := make(textproto.MIMEHeader)
	h.Set("Content-Disposition", `form-data; name="categories"`)
	h.Set("Content-Type", "application/json")
	fw, err := writer.CreatePart(h)
	if err != nil {
		panic(err)
	}
	if _, err = io.Copy(fw, strings.NewReader(`{"name": "bar"}`)); err != nil {
		panic(err)
	}
}

{ // Add file data
	fw, err := writer.CreateFormFile("file", "hello.txt")
	if err != nil {
		panic(err)
	}
	if _, err = io.Copy(fw, strings.NewReader("hello")); err != nil {
		panic(err)
	}
}

writer.Close()

req, err := http.NewRequest(http.MethodPost, "/test", bytes.NewReader(body.Bytes()))
if err != nil {
	panic(err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())

route, pathParams, err := router.FindRoute(req)
if err != nil {
	panic(err)
}

if err = openapi3filter.ValidateRequestBody(
	context.Background(),
	&openapi3filter.RequestValidationInput{
		Request:    req,
		PathParams: pathParams,
		Route:      route,
	},
	route.Operation.RequestBody.Value,
); err != nil {
	panic(err)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrBatchQueryLimitExceeded           = errors.New("batch query limit exceeded")
	ErrNotAllowIntrospectionQuery        = errors.New("introspection queries are not allowed")
	ErrGraphQLQueryNotFound              = errors.New("GraphQL query not found in the request")
	ErrWrongGraphQLQueryTypeInGETRequest = errors.New("wrong GraphQL query type in GET request")
	ErrFieldDuplicationFound             = errors.New("duplicate fields were found in the GraphQL document")
)
View Source
var ErrAuthenticationServiceMissing = errors.New("missing AuthenticationFunc")

ErrAuthenticationServiceMissing is returned when no authentication service is defined for the request validator

View Source
var ErrDecodingFailed = errors.New("the decoder returned the error")

ErrDecodingFailed is returned when the API FW got error or unexpected value from the decoder

View Source
var ErrInvalidEmptyValue = errors.New("empty value is not allowed")

ErrInvalidEmptyValue is returned when a value of a parameter or request body is empty while it's not allowed.

View Source
var ErrInvalidRequired = errors.New("value is required but missing")

ErrInvalidRequired is returned when a required value of a parameter or request body is not defined.

View Source
var ErrUnknownBodyParameter = errors.New("body parameter not defined in the OpenAPI specification")

ErrUnknownBodyParameter is returned when a body parameter not defined in the OpenAPI specification.

View Source
var ErrUnknownQueryParameter = errors.New("query parameter not defined in the OpenAPI specification")

ErrUnknownQueryParameter is returned when a query parameter not defined in the OpenAPI specification.

Functions

func FileBodyDecoder

func FileBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn, jsonParser *fastjson.Parser) (interface{}, error)

FileBodyDecoder is a body decoder that decodes a file body to a string.

func ParseGraphQLRequest added in v0.6.13

func ParseGraphQLRequest(ctx *fasthttp.RequestCtx, jsonParserPool *fastjson.ParserPool) ([]graphql.Request, error)

ParseGraphQLRequest function parses the GraphQL request

func RegisterBodyDecoder

func RegisterBodyDecoder(contentType string, decoder BodyDecoder)

RegisterBodyDecoder registers a request body's decoder for a content type.

If a decoder for the specified content type already exists, the function replaces it with the specified decoder. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

func RegisterBodyDecoderSuffix added in v0.7.1

func RegisterBodyDecoderSuffix(suffix string, decoder BodyDecoder)

RegisterBodyDecoderSuffix registers a request body's decoder for a content type suffix. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

func RegisterBodyEncoder added in v0.6.11

func RegisterBodyEncoder(contentType string, encoder BodyEncoder)

func UnmarshalGraphQLRequest added in v0.6.17

func UnmarshalGraphQLRequest(reader io.Reader, jsonParserPool *fastjson.ParserPool) ([]graphql.Request, error)

UnmarshalGraphQLRequest function parse the JSON document and build graphql.Request

func UnregisterBodyDecoder

func UnregisterBodyDecoder(contentType string)

UnregisterBodyDecoder dissociates a body decoder from a content type.

Decoding this content type will result in an error. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

func UnregisterBodyEncoder added in v0.6.11

func UnregisterBodyEncoder(contentType string)

This call is not thread-safe: body encoders should not be created/destroyed by multiple goroutines.

func ValidateGraphQLRequest added in v0.6.13

func ValidateGraphQLRequest(cfg *config.GraphQL, schema *graphql.Schema, r *graphql.Request) (*graphql.ValidationResult, error)

ValidateGraphQLRequest validates the GraphQL request

func ValidateParameter added in v0.6.11

func ValidateParameter(ctx context.Context, input *openapi3filter.RequestValidationInput, parameter *openapi3.Parameter) error

ValidateParameter validates a parameter's value by JSON schema. The function returns RequestError with a ParseError cause when unable to parse a value. The function returns RequestError with ErrInvalidRequired cause when a value of a required parameter is not defined. The function returns RequestError with ErrInvalidEmptyValue cause when a value of a required parameter is not defined. The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema.

func ValidateRequest

func ValidateRequest(ctx context.Context, input *openapi3filter.RequestValidationInput, jsonParser *fastjson.Parser) (err error)

ValidateRequest is used to validate the given input according to previous loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a non-nil error will be returned.

Note: One can tune the behavior of uniqueItems: true verification by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker

func ValidateRequestBody

func ValidateRequestBody(ctx context.Context, input *openapi3filter.RequestValidationInput, requestBody *openapi3.RequestBody, jsonParser *fastjson.Parser) error

ValidateRequestBody validates data of a request's body.

The function returns RequestError with ErrInvalidRequired cause when a value is required but not defined. The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema.

func ValidateResponse

func ValidateResponse(ctx context.Context, input *openapi3filter.ResponseValidationInput, jsonParser *fastjson.Parser) error

ValidateResponse is used to validate the given input according to previous loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a non-nil error will be returned.

Note: One can tune the behavior of uniqueItems: true verification by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker

func ValidateSecurityRequirements added in v0.6.11

func ValidateSecurityRequirements(ctx context.Context, input *openapi3filter.RequestValidationInput, srs openapi3.SecurityRequirements) error

ValidateSecurityRequirements goes through multiple OpenAPI 3 security requirements in order and returns nil on the first valid requirement. If no requirement is met, errors are returned in order.

Types

type BodyDecoder

type BodyDecoder func(io.Reader, http.Header, *openapi3.SchemaRef, EncodingFn, *fastjson.Parser) (interface{}, error)

BodyDecoder is an interface to decode a body of a request or response. An implementation must return a value that is a primitive, []interface{}, or map[string]interface{}.

func RegisteredBodyDecoder

func RegisteredBodyDecoder(contentType string) BodyDecoder

RegisteredBodyDecoder returns the registered body decoder for the given content type.

If no decoder was registered for the given content type, nil is returned. This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines.

type BodyEncoder added in v0.6.11

type BodyEncoder func(body interface{}) ([]byte, error)

func RegisteredBodyEncoder added in v0.6.11

func RegisteredBodyEncoder(contentType string) BodyEncoder

RegisteredBodyEncoder returns the registered body encoder for the given content type.

If no encoder was registered for the given content type, nil is returned. This call is not thread-safe: body encoders should not be created/destroyed by multiple goroutines.

type EncodingFn

type EncodingFn func(partName string) *openapi3.Encoding

EncodingFn is a function that returns an encoding of a request body's part.

type ParseError

type ParseError struct {
	Kind         ParseErrorKind
	Value        interface{}
	Reason       string
	ExpectedType string
	ValueStr     string
	Cause        error
	// contains filtered or unexported fields
}

ParseError describes errors which happens while parse operation's parameters, requestBody, or response.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Path

func (e *ParseError) Path() []interface{}

Path returns a path to the root cause.

func (*ParseError) RootCause

func (e *ParseError) RootCause() error

RootCause returns a root cause of ParseError.

func (ParseError) Unwrap

func (e ParseError) Unwrap() error

type ParseErrorKind

type ParseErrorKind int

ParseErrorKind describes a kind of ParseError. The type simplifies comparison of errors.

const (
	// KindOther describes an untyped parsing error.
	KindOther ParseErrorKind = iota
	// KindUnsupportedFormat describes an error that happens when a value has an unsupported format.
	KindUnsupportedFormat
	// KindInvalidFormat describes an error that happens when a value does not conform a format
	// that is required by a serialization method.
	KindInvalidFormat
)

type RequestParameterDetails added in v0.7.0

type RequestParameterDetails struct {
	Name        string `json:"name"`
	Placeholder string `json:"location"`
	Type        string `json:"type"`
}

RequestParameterDetails contains details about found unknown parameter

type RequestUnknownParameterError added in v0.6.12

type RequestUnknownParameterError struct {
	Parameters []RequestParameterDetails `json:"parameters"`
	Message    string                    `json:"message"`
}

RequestUnknownParameterError is returned by ValidateRequest when request does not match OpenAPI spec

func ValidateUnknownRequestParameters added in v0.6.12

func ValidateUnknownRequestParameters(ctx *fasthttp.RequestCtx, route *routers.Route, header http.Header, jsonParser *fastjson.Parser) (foundUnknownParams []RequestUnknownParameterError, valError error)

ValidateUnknownRequestParameters is used to get a list of request parameters that are not specified in the OpenAPI specification

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL