shared

package
v0.1.1-alpha Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultBasePath = "/"

DefaultBasePath is the Swagger 2.0 default basePath when absent.

View Source
const DefaultServersURL = "/"

DefaultServersURL is the OpenAPI 3.x default server URL when servers is absent or empty.

Variables

This section is empty.

Functions

func ApplySpecDefaults

func ApplySpecDefaults(cfg *ParseConfig) bool

ApplySpecDefaults returns true if the config has ApplySpecDefaults enabled. Callers use this to decide whether to fill in spec defaults for absent fields.

func FetchURL

func FetchURL(rawURL string) (data []byte, basePath string, err error)

FetchURL fetches a document from an HTTP/HTTPS URL and returns the raw bytes along with the base URL (directory) for resolving relative $ref references.

func FormatPath

func FormatPath(segments []string) string

FormatPath converts a slice of path segments to a dot-separated path string.

func FormatUnknownFieldMessage

func FormatUnknownFieldMessage(f UnknownField) string

FormatUnknownFieldMessage formats a single unknown field for display.

func GetAny

func GetAny(m map[string]interface{}, key string) interface{}

GetAny retrieves any value from a map, returning nil if not found.

func GetBool

func GetBool(m map[string]interface{}, key string) bool

GetBool retrieves a bool value from a map, returning false if not found or wrong type.

func GetBoolPtr

func GetBoolPtr(m map[string]interface{}, key string) *bool

GetBoolPtr retrieves a bool pointer from a map, returning nil if not found.

func GetFloat64

func GetFloat64(m map[string]interface{}, key string) float64

GetFloat64 retrieves a float64 value from a map, returning 0 if not found or wrong type.

func GetFloat64Ptr

func GetFloat64Ptr(m map[string]interface{}, key string) *float64

GetFloat64Ptr retrieves a float64 pointer from a map, returning nil if not found.

func GetInt

func GetInt(m map[string]interface{}, key string) int

GetInt retrieves an int value from a map, returning 0 if not found or wrong type.

func GetInterfaceSlice

func GetInterfaceSlice(m map[string]interface{}, key string) []interface{}

GetInterfaceSlice retrieves a slice of interface{} from a map, returning nil if not found.

func GetMap

func GetMap(m map[string]interface{}, key string) map[string]interface{}

GetMap retrieves a map value from a map, returning nil if not found or wrong type.

func GetRef

func GetRef(m map[string]interface{}) string

GetRef retrieves the $ref value from a map, returning empty string if not found.

func GetSlice

func GetSlice(m map[string]interface{}, key string) []interface{}

GetSlice retrieves a slice value from a map, returning nil if not found or wrong type.

func GetString

func GetString(m map[string]interface{}, key string) string

GetString retrieves a string value from a map, returning empty string if not found or wrong type.

func GetStringMap

func GetStringMap(m map[string]interface{}, key string) map[string]string

GetStringMap retrieves a map[string]string from a map, returning nil if not found.

func GetStringPtr

func GetStringPtr(m map[string]interface{}, key string) *string

GetStringPtr retrieves a string pointer from a map, returning nil if not found.

func GetStringSlice

func GetStringSlice(m map[string]interface{}, key string) []string

GetStringSlice retrieves a string slice from a map, returning nil if not found.

func GetUint64Ptr

func GetUint64Ptr(m map[string]interface{}, key string) *uint64

GetUint64Ptr retrieves a uint64 pointer from a map, returning nil if not found.

func HasKey

func HasKey(m map[string]interface{}, key string) bool

HasKey checks if a key exists in the map.

func HasRef

func HasRef(m map[string]interface{}) bool

HasRef checks if the map contains a $ref key.

func IsExtension

func IsExtension(key string) bool

IsExtension checks if a field name is an OpenAPI extension (x-*).

func IsExternalRef

func IsExternalRef(ref string) bool

IsExternalRef returns true if the ref points to an external file or URL.

func IsLocalRef

func IsLocalRef(ref string) bool

IsLocalRef returns true if the ref is a local JSON pointer (starts with #).

func IsRemoteRef

func IsRemoteRef(ref string) bool

IsRemoteRef returns true if the ref points to a remote URL (http:// or https://).

func Itoa

func Itoa(i int) string

Itoa converts an int to a string (simple implementation for indices).

func NodeGetAny

func NodeGetAny(node *yaml.Node, key string) interface{}

NodeGetAny gets the raw interface{} value by decoding the node.

func NodeGetBool

func NodeGetBool(node *yaml.Node, key string) bool

NodeGetBool gets a bool value from a mapping node by key.

func NodeGetBoolPtr

func NodeGetBoolPtr(node *yaml.Node, key string) *bool

NodeGetBoolPtr gets a *bool value from a mapping node by key.

func NodeGetFloat64

func NodeGetFloat64(node *yaml.Node, key string) float64

NodeGetFloat64 gets a float64 value from a mapping node by key.

func NodeGetFloat64Ptr

func NodeGetFloat64Ptr(node *yaml.Node, key string) *float64

NodeGetFloat64Ptr gets a *float64 value from a mapping node by key.

func NodeGetInt

func NodeGetInt(node *yaml.Node, key string) int

NodeGetInt gets an int value from a mapping node by key.

func NodeGetIntPtr

func NodeGetIntPtr(node *yaml.Node, key string) *int

NodeGetIntPtr gets a *int value from a mapping node by key.

func NodeGetKeyNode

func NodeGetKeyNode(node *yaml.Node, key string) *yaml.Node

NodeGetKeyNode gets the key node itself (for position info).

func NodeGetRef

func NodeGetRef(node *yaml.Node) string

NodeGetRef retrieves the $ref value from a node, returning empty string if not found.

func NodeGetString

func NodeGetString(node *yaml.Node, key string) string

NodeGetString gets a string value from a mapping node by key.

func NodeGetStringMap

func NodeGetStringMap(node *yaml.Node, key string) map[string]string

NodeGetStringMap gets a map[string]string from a mapping node by key.

func NodeGetStringSlice

func NodeGetStringSlice(node *yaml.Node, key string) []string

NodeGetStringSlice gets a string slice from a mapping node by key.

func NodeGetUint64Ptr

func NodeGetUint64Ptr(node *yaml.Node, key string) *uint64

NodeGetUint64Ptr gets a *uint64 value from a mapping node by key.

func NodeGetValue

func NodeGetValue(node *yaml.Node, key string) *yaml.Node

NodeGetValue gets a child node by key from a mapping node. Returns nil if not found or if node is not a mapping.

func NodeHasKey

func NodeHasKey(node *yaml.Node, key string) bool

NodeHasKey checks if a key exists in a mapping node.

func NodeHasRef

func NodeHasRef(node *yaml.Node) bool

NodeHasRef checks if the node contains a $ref key.

func NodeIsMapping

func NodeIsMapping(node *yaml.Node) bool

NodeIsMapping checks if a node is a mapping node.

func NodeIsScalar

func NodeIsScalar(node *yaml.Node) bool

NodeIsScalar checks if a node is a scalar node.

func NodeIsSequence

func NodeIsSequence(node *yaml.Node) bool

NodeIsSequence checks if a node is a sequence node.

func NodeKeys

func NodeKeys(node *yaml.Node) []string

NodeKeys returns all keys in a mapping node.

func NodeMapPairs

func NodeMapPairs(node *yaml.Node) iter.Seq2[string, *yaml.Node]

NodeMapPairs iterates over key-value pairs in a mapping node (single-pass). Returns a range-over-func iterator for use with Go 1.23+ range syntax.

func NodeToInterface

func NodeToInterface(node *yaml.Node) interface{}

NodeToInterface converts a yaml.Node to interface{} (for Raw storage).

func NodeToMap

func NodeToMap(node *yaml.Node) map[string]*yaml.Node

NodeToMap converts a mapping node to iterate over key-value pairs. Returns key string, value node pairs.

func NodeToSlice

func NodeToSlice(node *yaml.Node) []*yaml.Node

NodeToSlice converts a sequence node to a slice of nodes.

func ParseExtensions

func ParseExtensions(m map[string]interface{}) map[string]interface{}

ParseExtensions extracts extension fields (x-*) from a map.

func ParseNodeExtensions

func ParseNodeExtensions(node *yaml.Node) map[string]interface{}

ParseNodeExtensions extracts extension fields (x-*) from a yaml.Node.

func ParseOperationRef

func ParseOperationRef(ref string) (path string, method string, err error)

ParseOperationRef parses an operationRef JSON pointer like "#/paths/~1users~1{id}/get" into the path pattern and HTTP method. Returns ("", "", err) if the ref doesn't match the expected /paths/{path}/{method} format.

func ResolveJSONPointer

func ResolveJSONPointer(root *yaml.Node, pointer string) (*yaml.Node, error)

ResolveJSONPointer resolves a JSON pointer (RFC 6901) within a yaml.Node tree. The pointer should start with "/" (e.g. "/components/schemas/Pet"). Handles both mapping nodes (by key lookup) and sequence nodes (by index).

func ServersAbsentOrEmpty

func ServersAbsentOrEmpty(node *yaml.Node) bool

ServersAbsentOrEmpty returns true if the servers node is nil, or is a sequence with no elements. Used with ApplySpecDefaults to apply the OpenAPI 3.x default.

func SplitRef

func SplitRef(ref string) (filePath, pointer string)

SplitRef splits a $ref string into a file path and a JSON pointer. Examples:

"#/components/schemas/Pet"          → ("", "/components/schemas/Pet")
"./schemas/pet.yaml"                → ("./schemas/pet.yaml", "")
"./common.yaml#/definitions/Error"  → ("./common.yaml", "/definitions/Error")
"Pet"                               → ("", "Pet")  (bare name, e.g. Swagger 2.0)

func ToSet

func ToSet(fields []string) map[string]struct{}

ToSet converts a slice of field names to a set for O(1) lookup.

Types

type ParseConfig

type ParseConfig struct {
	// DetectUnknownFields enables detection and reporting of fields not
	// recognized as valid OpenAPI fields for their context.
	DetectUnknownFields bool

	// ResolveInternalRefs enables resolution of local JSON pointer $refs (#/...).
	ResolveInternalRefs bool

	// ResolveExternalRefs enables resolution of external file and URL $refs.
	ResolveExternalRefs bool

	// ApplySpecDefaults fills in OpenAPI-specified default values when optional
	// fields are absent (e.g., servers absent → [{ url: "/" }]).
	ApplySpecDefaults bool
}

ParseConfig controls which features are enabled during parsing. A nil config is treated as All() — all features enabled.

func All

func All() *ParseConfig

All returns a config with all features enabled. This is the default when no config (nil) is passed to a Parse function.

func Defaults

func Defaults(cfg *ParseConfig) *ParseConfig

Defaults returns the provided config if non-nil, otherwise All().

func FirstConfig

func FirstConfig(cfgs []*ParseConfig) *ParseConfig

FirstConfig extracts the first non-nil config from a variadic list, falling back to All() if none provided.

func None

func None() *ParseConfig

None returns a config with all features disabled. Only basic parsing is performed — no unknown field detection, no $ref resolution, and no error collection on Trix.Errors.

type ParseError

type ParseError struct {
	Path    []string // JSON path where error occurred
	Message string   // Error message
	Kind    string   // Error kind: "error" or "unknown_field"
	Cause   error    // Wrapped error if any
	Line    int      // Line number (1-based, 0 if unknown)
	Column  int      // Column number (1-based, 0 if unknown)
}

ParseError represents an error that occurred during parsing, including the JSON path and source location where the error occurred.

func NewParseError

func NewParseError(path []string, format string, args ...interface{}) *ParseError

NewParseError creates a new ParseError with the given path and message.

func NewParseErrorWithCause

func NewParseErrorWithCause(path []string, cause error, format string, args ...interface{}) *ParseError

NewParseErrorWithCause creates a new ParseError that wraps another error.

func (*ParseError) Error

func (e *ParseError) Error() string

Error implements the error interface.

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap returns the underlying cause error for use with errors.Is/As.

type RefResolver

type RefResolver struct {
	// BasePath is the directory of the root document, used to resolve relative file paths.
	BasePath string

	// Root is the yaml.Node of the root document.
	Root *yaml.Node

	// Fs is the filesystem to use for reading external files.
	// Defaults to afero.OsFs if nil.
	Fs afero.Fs

	// HTTPClient is the HTTP client used for fetching remote $ref URLs.
	// Defaults to a client with a 30-second timeout.
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

RefResolver resolves $ref references — local (JSON pointer), external (file), and remote (HTTP/HTTPS URL). It caches loaded documents and detects circular references. It also supports JSON Schema anchors ($anchor, $dynamicAnchor, $dynamicRef).

func NewRefResolver

func NewRefResolver(basePath string, root *yaml.Node) *RefResolver

NewRefResolver creates a new RefResolver using the real OS filesystem. basePath is the directory containing the root document. root is the parsed yaml.Node of the root document.

func NewRefResolverWithFs

func NewRefResolverWithFs(basePath string, root *yaml.Node, fs afero.Fs) *RefResolver

NewRefResolverWithFs creates a new RefResolver with a custom filesystem. This is useful for testing with in-memory filesystems.

func (*RefResolver) BuildAnchorIndex

func (r *RefResolver) BuildAnchorIndex(docKey string, root *yaml.Node)

BuildAnchorIndex scans a YAML document tree for $anchor values and registers them in the anchor cache. docKey identifies which document this is (use "" for the root document).

func (*RefResolver) BuildDynamicAnchorIndex

func (r *RefResolver) BuildDynamicAnchorIndex(root *yaml.Node)

BuildDynamicAnchorIndex scans a YAML document tree for $dynamicAnchor values and registers them. This is used for $dynamicRef resolution. In a parser context (no validation scope), we resolve $dynamicRef statically to the first matching $dynamicAnchor in the document.

func (*RefResolver) Resolve

func (r *RefResolver) Resolve(ref string) (*ResolveResult, error)

Resolve resolves a $ref string to a yaml.Node. For local refs (#/path/to/thing), resolves within the root document. For external refs (file.yaml or file.yaml#/pointer), loads the file and resolves. Returns ResolveResult with Circular=true if a circular reference is detected.

func (*RefResolver) ResolveDynamicRef

func (r *RefResolver) ResolveDynamicRef(ref string) (*ResolveResult, error)

ResolveDynamicRef resolves a $dynamicRef string (e.g. "#meta") to the schema node that has a matching $dynamicAnchor. Returns an error if not found.

func (*RefResolver) ResolveMapping

func (r *RefResolver) ResolveMapping(value string) (*ResolveResult, error)

ResolveMapping resolves a discriminator mapping value to a YAML node. The value can be:

  • A bare schema name (e.g. "Dog") → resolved as #/components/schemas/Dog
  • A $ref string (e.g. "#/components/schemas/Dog" or "./models/dog.yaml")

type ResolveResult

type ResolveResult struct {
	// Node is the resolved yaml.Node.
	Node *yaml.Node

	// Circular is true if a circular reference was detected.
	Circular bool
}

ResolveResult contains the result of resolving a $ref.

type UnknownField

type UnknownField struct {
	// Path is the JSON path to the parent object containing the unknown field.
	// Example: "paths./pets.get.responses.200"
	Path string

	// Key is the name of the unknown field.
	Key string

	// Name is an alias for Key, kept for backward compatibility with openapi20.
	Name string

	// Line is the source line number (1-based) where the field was found.
	Line int

	// Column is the source column number (1-based) where the field was found.
	Column int
}

UnknownField represents a field in the source document that was not recognized as a valid OpenAPI field for its context.

func DetectUnknownNodeFields

func DetectUnknownNodeFields(node *yaml.Node, knownFields map[string]struct{}, path string) []UnknownField

DetectUnknownNodeFields checks a yaml.Node for keys that are not in the known fields set and not extensions (x-*). Returns a slice of unknown fields.

type UnknownFieldError

type UnknownFieldError struct {
	Fields []UnknownField
}

UnknownFieldError is an error type that wraps unknown fields for reporting.

func (*UnknownFieldError) Error

func (e *UnknownFieldError) Error() string

Error implements the error interface.

Jump to

Keyboard shortcuts

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