helpers

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2025 License: MIT Imports: 14 Imported by: 2

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"
	Schema                    = "schema"
	ResponseBodyValidation    = "response"
	RequestBodyContentType    = "contentType"
	RequestMissingOperation   = "missingOperation"
	ResponseBodyResponseCode  = "statusCode"
	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"
	JSONType                  = "json"
	ContentTypeHeader         = "Content-Type"
	AuthorizationHeader       = "Authorization"
	Charset                   = "charset"
	Boundary                  = "boundary"
	Preferred                 = "preferred"
	FailSegment               = "**&&FAIL&&**"
)

Variables

View Source
var (
	IgnorePattern     = `^\b(anyOf|allOf|oneOf|validation) failed\b`
	IgnorePolyPattern = `^\b(anyOf|allOf|oneOf) failed\b`
)

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

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

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

func ConstructKVFromLabelEncoding

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

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

func ConstructKVFromMatrixCSV

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

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

func ConstructMapFromCSV

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

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

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

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

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

func ConstructParamMapFromPipeEncoding

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

ConstructParamMapFromPipeEncoding will construct a map from the query parameters that are encoded as pipe separated values. Perhaps the most sane way to delimit/encode properties.

func ConstructParamMapFromQueryParamInput

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

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

func ConstructParamMapFromSpaceEncoding

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

ConstructParamMapFromSpaceEncoding will construct a map from the query parameters that are encoded as space delimited values. This is perhaps the worst way to delimit anything other than a paragraph of text.

func DoesFormParamContainDelimiter

func DoesFormParamContainDelimiter(value, style string) bool

DoesFormParamContainDelimiter will determine if a form parameter contains a delimiter.

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 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 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.

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.

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.

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