helpers

package
v0.13.2 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 18 Imported by: 3

Documentation

Overview

Package helpers contains helper and utility functions used by the validator. Trying to avoid using the package name utils anymore, as it's too generic and can cause conflicts with other packages - however I feel this pattern will suffer the exact same fate with time.

Index

Constants

View Source
const (
	ParameterValidation       = "parameter"
	ParameterValidationPath   = "path"
	ParameterValidationQuery  = "query"
	ParameterValidationHeader = "header"
	ParameterValidationCookie = "cookie"
	RequestValidation         = "request"
	RequestBodyValidation     = "requestBody"
	XmlValidation             = "xmlValidation"
	XmlValidationPrefix       = "prefix"
	XmlValidationNamespace    = "namespace"
	URLEncodedValidation      = "urlEncodedValidation"
	InvalidTypeEncoding       = "invalidTypeEncoding"
	ReservedValues            = "reservedValues"
	Schema                    = "schema"
	ResponseBodyValidation    = "response"
	RequestBodyContentType    = "contentType"
	// Deprecated: use ValidationMissingOperation
	RequestMissingOperation    = "missingOperation"
	PathValidation             = "path"
	ValidationMissing          = "missing"
	ValidationMissingOperation = "missingOperation"
	ResponseBodyResponseCode   = "statusCode"
	SecurityValidation         = "security"
	DocumentValidation         = "document"
	SpaceDelimited             = "spaceDelimited"
	PipeDelimited              = "pipeDelimited"
	DefaultDelimited           = "default"
	MatrixStyle                = "matrix"
	LabelStyle                 = "label"
	Pipe                       = "|"
	Comma                      = ","
	Space                      = " "
	SemiColon                  = ";"
	Asterisk                   = "*"
	Period                     = "."
	Equals                     = "="
	Integer                    = "integer"
	Number                     = "number"
	Slash                      = "/"
	Object                     = "object"
	String                     = "string"
	Array                      = "array"
	Boolean                    = "boolean"
	DeepObject                 = "deepObject"
	Header                     = "header"
	Cookie                     = "cookie"
	Path                       = "path"
	Form                       = "form"
	Query                      = "query"
	JSONContentType            = "application/json"
	URLEncodedContentType      = "application/x-www-form-urlencoded"
	JSONType                   = "json"
	ContentTypeHeader          = "Content-Type"
	AuthorizationHeader        = "Authorization"
	Charset                    = "charset"
	Boundary                   = "boundary"
	Preferred                  = "preferred"
	FailSegment                = "**&&FAIL&&**"
)

Variables

View Source
var (
	// Ignore generic poly errors that just say "none matched" since we get specific errors
	// But keep errors that say which subschemas matched (for multiple match scenarios)
	IgnorePattern     = `^'?(anyOf|allOf|oneOf|validation)'? failed(, none matched)?$`
	IgnorePolyPattern = `^'?(anyOf|allOf|oneOf)'? failed(, none matched)?$`
)
View Source
var (
	DefaultPatternRegex       = regexp.MustCompile("^([^/]*)$")
	DefaultPatternRegexString = DefaultPatternRegex.String()
)

IgnorePolyRegex is a regular expression that matches the IgnorePattern

IgnoreRegex is a regular expression that matches the IgnorePattern

Functions

func BraceIndices added in v0.4.0

func BraceIndices(s string) ([]int, error)

BraceIndices returns the indices of the opening and closing braces in a string.

It scans the input string `s` and identifies the positions of matching pairs of braces ('{' and '}'). The function ensures that the braces are balanced and properly nested.

If the braces are unbalanced or improperly nested, an error is returned.

Parameters:

  • s: The input string to scan for braces.

Returns:

  • []int: A slice of integers where each pair of indices represents the start and end positions of a matching pair of braces.
  • error: An error if the braces are unbalanced or improperly nested.

Example:

indices, err := BraceIndices("/orders/{id}/items/{itemId}")
// indices: [8, 12, 19, 26]
// err: nil

func CollapseCSVIntoFormStyle

func CollapseCSVIntoFormStyle(key string, value string) string

func CollapseCSVIntoPipeDelimitedStyle

func CollapseCSVIntoPipeDelimitedStyle(key string, values []string) string

func CollapseCSVIntoSpaceDelimitedStyle

func CollapseCSVIntoSpaceDelimitedStyle(key string, values []string) string

func ConfigureCompiler added in v0.4.0

func ConfigureCompiler(c *jsonschema.Compiler, o *config.ValidationOptions)

ConfigureCompiler configures a JSON Schema compiler with the desired behavior.

func ConstructKVFromCSV deprecated

func ConstructKVFromCSV(values string) map[string]interface{}

ConstructKVFromCSV will construct a map from a comma separated value string that denotes key value pairs.

Deprecated: use ConstructKVFromCSVWithSchema instead.

func ConstructKVFromCSVWithSchema added in v0.13.2

func ConstructKVFromCSVWithSchema(values string, sch *base.Schema) map[string]interface{}

ConstructKVFromCSVWithSchema constructs a map from a comma-separated key=value string, using the object schema to determine property types before casting.

func ConstructKVFromLabelEncoding deprecated

func ConstructKVFromLabelEncoding(values string) map[string]interface{}

ConstructKVFromLabelEncoding will construct a map from a period separated value string that denotes key value pairs.

Deprecated: use ConstructKVFromLabelEncodingWithSchema instead.

func ConstructKVFromLabelEncodingWithSchema added in v0.13.2

func ConstructKVFromLabelEncodingWithSchema(values string, sch *base.Schema) map[string]interface{}

ConstructKVFromLabelEncodingWithSchema constructs a map from a period-separated key=value string, using the object schema to determine property types before casting.

func ConstructKVFromMatrixCSV deprecated

func ConstructKVFromMatrixCSV(values string) map[string]interface{}

ConstructKVFromMatrixCSV will construct a map from a semicolon separated value string that denotes key value pairs.

Deprecated: use ConstructKVFromMatrixCSVWithSchema instead.

func ConstructKVFromMatrixCSVWithSchema added in v0.13.2

func ConstructKVFromMatrixCSVWithSchema(values string, sch *base.Schema) map[string]interface{}

ConstructKVFromMatrixCSVWithSchema constructs a map from a semicolon-separated key=value string, using the object schema to determine property types before casting.

func ConstructMapFromCSV deprecated

func ConstructMapFromCSV(csv string) map[string]interface{}

ConstructMapFromCSV will construct a map from a comma separated value string.

Deprecated: use ConstructMapFromCSVWithSchema instead.

func ConstructMapFromCSVWithSchema added in v0.13.2

func ConstructMapFromCSVWithSchema(csv string, sch *base.Schema) map[string]interface{}

ConstructMapFromCSVWithSchema constructs a map from a comma separated value string, using the object schema to determine property types before casting.

func ConstructParamMapFromDeepObjectEncoding

func ConstructParamMapFromDeepObjectEncoding(values []*QueryParam, sch *base.Schema) map[string]interface{}

ConstructParamMapFromDeepObjectEncoding will construct a map from the query parameters that are encoded as deep objects. It's kind of a crazy way to do things, but hey, each to their own.

func ConstructParamMapFromFormEncodingArray deprecated

func ConstructParamMapFromFormEncodingArray(values []*QueryParam) map[string]interface{}

ConstructParamMapFromFormEncodingArray will construct a map from the query parameters that are encoded as form encoded values.

Deprecated: use ConstructParamMapFromFormEncodingArrayWithSchema instead.

func ConstructParamMapFromFormEncodingArrayWithSchema added in v0.13.2

func ConstructParamMapFromFormEncodingArrayWithSchema(values []*QueryParam, sch *base.Schema) map[string]interface{}

ConstructParamMapFromFormEncodingArrayWithSchema constructs a map from form-encoded query parameters, using the object schema to determine property types before casting.

func ConstructParamMapFromPipeEncoding deprecated

func ConstructParamMapFromPipeEncoding(values []*QueryParam) map[string]interface{}

ConstructParamMapFromPipeEncoding will construct a map from the query parameters that are encoded as pipe separated values.

Deprecated: use ConstructParamMapFromPipeEncodingWithSchema instead.

func ConstructParamMapFromPipeEncodingWithSchema added in v0.13.2

func ConstructParamMapFromPipeEncodingWithSchema(values []*QueryParam, sch *base.Schema) map[string]interface{}

ConstructParamMapFromPipeEncodingWithSchema constructs a map from pipe-delimited query parameters, using the object schema to determine property types before casting.

func ConstructParamMapFromQueryParamInput deprecated

func ConstructParamMapFromQueryParamInput(values map[string][]*QueryParam) map[string]interface{}

ConstructParamMapFromQueryParamInput will construct a param map from an existing map of *QueryParam slices.

Deprecated: use ConstructParamMapFromQueryParamInputWithSchema instead.

func ConstructParamMapFromQueryParamInputWithSchema added in v0.13.2

func ConstructParamMapFromQueryParamInputWithSchema(values map[string][]*QueryParam, sch *base.Schema) map[string]interface{}

ConstructParamMapFromQueryParamInputWithSchema constructs a param map from an existing map of *QueryParam slices, using the object schema to determine property types before casting.

func ConstructParamMapFromSpaceEncoding deprecated

func ConstructParamMapFromSpaceEncoding(values []*QueryParam) map[string]interface{}

ConstructParamMapFromSpaceEncoding will construct a map from the query parameters that are encoded as space delimited values.

Deprecated: use ConstructParamMapFromSpaceEncodingWithSchema instead.

func ConstructParamMapFromSpaceEncodingWithSchema added in v0.13.2

func ConstructParamMapFromSpaceEncodingWithSchema(values []*QueryParam, sch *base.Schema) map[string]interface{}

ConstructParamMapFromSpaceEncodingWithSchema constructs a map from space-delimited query parameters, using the object schema to determine property types before casting.

func ConstructParameterJSONPointer added in v0.13.0

func ConstructParameterJSONPointer(pathTemplate, method, paramName, keyword string) string

ConstructParameterJSONPointer constructs a full JSON Pointer path for a parameter in the OpenAPI specification. Format: /paths/{path}/{method}/parameters/{paramName}/schema/{keyword} The path segment is automatically escaped according to RFC 6901. The keyword can be a simple keyword like "type" or a nested path like "items/type".

func ConstructResponseHeaderJSONPointer added in v0.13.0

func ConstructResponseHeaderJSONPointer(pathTemplate, method, statusCode, headerName, keyword string) string

ConstructResponseHeaderJSONPointer constructs a full JSON Pointer path for a response header in the OpenAPI specification. Format: /paths/{path}/{method}/responses/{statusCode}/headers/{headerName}/{keyword} The path segment is automatically escaped according to RFC 6901.

func ConvertStringLocationToPathSegments added in v0.5.0

func ConvertStringLocationToPathSegments(instanceLocation string) []string

ConvertStringLocationToPathSegments converts a string-based instance location to path segments array Handles edge cases like empty strings and root-only paths

func DoesFormParamContainDelimiter

func DoesFormParamContainDelimiter(value, style string) bool

DoesFormParamContainDelimiter will determine if a form parameter contains a delimiter.

func EffectiveSecurityForOperation added in v0.13.2

func EffectiveSecurityForOperation(request *http.Request, item *v3.PathItem, docSecurity []*base.SecurityRequirement) []*base.SecurityRequirement

EffectiveSecurityForOperation returns the security requirements that apply to the operation matched by request method. It implements OpenAPI's inheritance rule:

  • If the operation defines security (even an empty array), use that.
  • Otherwise, fall back to the document-level global security.
  • Returns nil only when neither level defines security.

func EscapeJSONPointerSegment added in v0.13.0

func EscapeJSONPointerSegment(segment string) string

EscapeJSONPointerSegment escapes a single segment for use in a JSON Pointer (RFC 6901). It replaces '~' with '~0' and '/' with '~1'.

func ExplodeQueryValue

func ExplodeQueryValue(value, style string) []string

ExplodeQueryValue will explode a query value based on the style (space, pipe, or form/default).

func ExtractContentType

func ExtractContentType(contentType string) (string, string, string)

ExtractContentType extracts the content type from the request header. First return argument is the content type of the request.The second (optional) argument is the charset of the request. The third (optional) argument is the boundary of the type (only used with forms really).

func ExtractFieldNameFromInstanceLocation added in v0.5.0

func ExtractFieldNameFromInstanceLocation(instanceLocation []string) string

ExtractFieldNameFromInstanceLocation returns the last segment of the instance location as the field name

func ExtractFieldNameFromStringLocation added in v0.5.0

func ExtractFieldNameFromStringLocation(instanceLocation string) string

ExtractFieldNameFromStringLocation returns the last segment of the instance location as the field name when the location is provided as a string path

func ExtractJSONPathFromInstanceLocation added in v0.5.0

func ExtractJSONPathFromInstanceLocation(instanceLocation []string) string

ExtractJSONPathFromInstanceLocation creates a JSONPath string from instance location segments

func ExtractJSONPathFromStringLocation added in v0.5.0

func ExtractJSONPathFromStringLocation(instanceLocation string) string

ExtractJSONPathFromStringLocation creates a JSONPath string from string-based instance location

func ExtractJSONPathFromValidationError added in v0.4.5

func ExtractJSONPathFromValidationError(e *jsonschema.ValidationError) string

ExtractJSONPathFromValidationError traverses and processes a ValidationError to construct a JSONPath string representation of its instance location.

func ExtractJSONPathsFromValidationErrors added in v0.4.5

func ExtractJSONPathsFromValidationErrors(errors []*jsonschema.ValidationError) []string

ExtractJSONPathsFromValidationErrors takes a slice of ValidationError pointers and returns a slice of JSONPath strings

func ExtractOperation

func ExtractOperation(request *http.Request, item *v3.PathItem) *v3.Operation

ExtractOperation extracts the operation from the path item based on the request method. If there is no matching operation found, then nil is returned.

func ExtractParamsForOperation

func ExtractParamsForOperation(request *http.Request, item *v3.PathItem) []*v3.Parameter

ExtractParamsForOperation will extract the parameters for the operation based on the request method. Both the path level params and the method level params will be returned.

func ExtractSecurityForOperation deprecated added in v0.0.33

func ExtractSecurityForOperation(request *http.Request, item *v3.PathItem) []*base.SecurityRequirement

ExtractSecurityForOperation will extract the security requirements for the operation based on the request method.

Deprecated: use EffectiveSecurityForOperation instead, which also handles document-level global security inheritance per the OpenAPI specification.

func ExtractSecurityHeaderNames added in v0.10.1

func ExtractSecurityHeaderNames(
	security []*base.SecurityRequirement,
	securitySchemes map[string]*v3.SecurityScheme,
) []string

ExtractSecurityHeaderNames extracts header names from applicable security schemes. Returns header names from apiKey schemes with in:"header", plus "Authorization" for http/oauth2/openIdConnect schemes.

This function is used by strict mode validation to recognize security headers as "declared" headers that should not trigger undeclared header errors.

func GetRegexForPath added in v0.4.0

func GetRegexForPath(tpl string) (*regexp.Regexp, error)

GetRegexForPath returns a compiled regular expression for the given path template.

This function takes a path template string `tpl` and generates a regular expression that matches the structure of the template. The template can include placeholders enclosed in braces `{}` with optional custom patterns.

Placeholders in the template can be defined as:

  • `{name}`: Matches any sequence of characters except '/'
  • `{name:pattern}`: Matches the specified custom pattern

The function ensures that the template is well-formed, with balanced and properly nested braces. If the template is invalid, an error is returned.

Parameters:

  • tpl: The path template string to convert into a regular expression.

Returns:

  • *regexp.Regexp: A compiled regular expression that matches the template.
  • error: An error if the template is invalid or the regular expression cannot be compiled.

Example:

regex, err := GetRegexForPath("/orders/{id:[0-9]+}/items/{itemId}")
// regex: ^/orders/([0-9]+)/items/([^/]+)$
// err: nil

func NewCompiledSchema added in v0.4.0

func NewCompiledSchema(name string, jsonSchema []byte, o *config.ValidationOptions) (*jsonschema.Schema, error)

NewCompiledSchema establishes a programmatic representation of a JSON Schema document that is used for validation. Defaults to OpenAPI 3.1+ behavior (strict JSON Schema compliance).

func NewCompiledSchemaWithVersion added in v0.6.0

func NewCompiledSchemaWithVersion(name string, jsonSchema []byte, options *config.ValidationOptions, version float32) (*jsonschema.Schema, error)

NewCompiledSchemaWithVersion establishes a programmatic representation of a JSON Schema document that is used for validation. The version parameter determines which OpenAPI keywords are allowed: - version 3.0: Allows OpenAPI 3.0 keywords like 'nullable' - version 3.1+: Rejects OpenAPI 3.0 keywords like 'nullable' (strict JSON Schema compliance)

func NewCompilerLoader added in v0.2.0

func NewCompilerLoader() jsonschema.SchemeURLLoader

func NewCompilerWithOptions added in v0.4.0

func NewCompilerWithOptions(o *config.ValidationOptions) *jsonschema.Compiler

NewCompilerWithOptions mints a new JSON schema compiler with custom configuration.

func VersionToFloat added in v0.7.0

func VersionToFloat(version string) float32

VersionToFloat converts a version string to a float32 for easier comparison.

Types

type HTTPURLLoader added in v0.2.0

type HTTPURLLoader http.Client

HTTPURLLoader is a type that implements the Loader interface for loading schemas from HTTP URLs. this change was made in jsonschema v6. The httploader package was removed and the HTTPURLLoader type was introduced. https://github.com/santhosh-tekuri/jsonschema/blob/boon/example_http_test.go TODO: make all this stuff configurable, right now it's all hard wired and not very flexible.

use interfaces and abstractions on all this.

func NewHTTPURLLoader added in v0.2.0

func NewHTTPURLLoader(insecure bool) *HTTPURLLoader

func (*HTTPURLLoader) Load added in v0.2.0

func (l *HTTPURLLoader) Load(url string) (any, error)

type QueryParam

type QueryParam struct {
	Key      string
	Values   []string
	Property string
}

QueryParam is a struct that holds the key, values and property name for a query parameter it's used for complex query types that need to be parsed and tracked differently depending on the encoding styles used.

Jump to

Keyboard shortcuts

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