Documentation
¶
Overview ¶
Package pathutil provides efficient path building utilities for OpenAPI document traversal.
The primary type is PathBuilder, which uses push/pop semantics to build paths incrementally without allocating intermediate strings. This is particularly useful in recursive traversal where paths are built on each recursive call but only used when reporting errors or differences.
PathBuilder Usage ¶
Use Get to obtain a pooled PathBuilder, and Put to return it:
path := pathutil.Get()
defer pathutil.Put(path)
path.Push("properties")
path.Push(propName)
// ... recurse ...
path.Pop()
path.Pop()
// Only call String() when needed (e.g., reporting an error)
if hasError {
return fmt.Errorf("error at %s", path.String())
}
Array indices are supported via PathBuilder.PushIndex:
path.Push("items")
path.PushIndex(0) // produces "items[0]"
Reference Builders ¶
The package also provides functions for building JSON Pointer references to OpenAPI components:
ref := pathutil.SchemaRef("Pet") // "#/components/schemas/Pet"
ref := pathutil.DefinitionRef("Pet") // "#/definitions/Pet"
These use simple string concatenation which Go optimizes well for two operands, avoiding the overhead of fmt.Sprintf.
Version-aware helpers handle OAS 2.0 vs 3.x differences:
ref := pathutil.ParameterRef("limit", true) // "#/parameters/limit" (OAS 2.0)
ref := pathutil.ParameterRef("limit", false) // "#/components/parameters/limit" (OAS 3.x)
Output Path Sanitization ¶
SanitizeOutputPath validates and cleans output file paths for security. It rejects directory traversal ("..") and symlinks:
safe, err := pathutil.SanitizeOutputPath(userProvidedPath)
if err != nil {
return err // path traversal or symlink detected
}
Index ¶
- Constants
- Variables
- func CallbackRef(name string) string
- func DefinitionRef(name string) string
- func EscapeRefToken(name string) string
- func ExampleRef(name string) string
- func HeaderRef(name string) string
- func LinkRef(name string) string
- func ParameterRef(name string, oas2 bool) string
- func PathItemRef(name string) string
- func Put(p *PathBuilder)
- func RequestBodyRef(name string) string
- func ResponseRef(name string, oas2 bool) string
- func SanitizeOutputPath(path string) (string, error)
- func SchemaRef(name string) string
- func SecuritySchemeRef(name string, oas2 bool) string
- func UnescapeRefToken(token string) string
- type PathBuilder
Constants ¶
const ( RefPrefixDefinitions = "#/definitions/" RefPrefixParameters = "#/parameters/" RefPrefixResponses = "#/responses/" RefPrefixSecurityDefinitions = "#/securityDefinitions/" )
OAS 2.0 reference prefixes
const ( RefPrefixSchemas = "#/components/schemas/" RefPrefixParameters3 = "#/components/parameters/" RefPrefixResponses3 = "#/components/responses/" RefPrefixExamples = "#/components/examples/" RefPrefixRequestBodies = "#/components/requestBodies/" RefPrefixHeaders = "#/components/headers/" RefPrefixSecuritySchemes = "#/components/securitySchemes/" RefPrefixLinks = "#/components/links/" RefPrefixCallbacks = "#/components/callbacks/" RefPrefixPathItems = "#/components/pathItems/" )
OAS 3.x reference prefixes
Variables ¶
var PathParamRegex = regexp.MustCompile(`\{([^}]+)\}`)
PathParamRegex matches path template parameters like {paramName}. It captures the parameter name inside the braces.
Functions ¶
func CallbackRef ¶
CallbackRef builds "#/components/callbacks/{name}" (OAS 3.x only).
func DefinitionRef ¶
DefinitionRef builds "#/definitions/{name}" (OAS 2.0).
func EscapeRefToken ¶ added in v1.54.0
EscapeRefToken escapes a component name for use as a single JSON Pointer token, per RFC 6901: "~" becomes "~0" and "/" becomes "~1".
Order matters — "~" must be escaped first, or the "~" introduced by escaping "/" would itself be escaped and produce "~01".
OAS 2.0 places no charset constraint on the keys of the root-level parameters, definitions, and responses objects, so a name containing either character is legitimate and must be escaped for a document to reference it. Building a reference by raw concatenation instead produces a pointer that names a different location and therefore never matches.
func ExampleRef ¶
ExampleRef builds "#/components/examples/{name}" (OAS 3.x only).
func ParameterRef ¶
ParameterRef builds the appropriate parameter ref. If oas2 is true, returns "#/parameters/{name}", otherwise "#/components/parameters/{name}".
func PathItemRef ¶
PathItemRef builds "#/components/pathItems/{name}" (OAS 3.1+ only).
func RequestBodyRef ¶
RequestBodyRef builds "#/components/requestBodies/{name}" (OAS 3.x only).
func ResponseRef ¶
ResponseRef builds the appropriate response ref. If oas2 is true, returns "#/responses/{name}", otherwise "#/components/responses/{name}".
func SanitizeOutputPath ¶ added in v1.52.0
SanitizeOutputPath validates and cleans an output file path. It resolves ".." components via filepath.Clean + filepath.Abs and rejects paths that resolve to symlinks. New files in existing directories are accepted. Returns the cleaned absolute path.
func SecuritySchemeRef ¶
SecuritySchemeRef builds the appropriate security scheme ref. If oas2 is true, returns "#/securityDefinitions/{name}", otherwise "#/components/securitySchemes/{name}".
func UnescapeRefToken ¶ added in v1.54.0
UnescapeRefToken reverses EscapeRefToken, recovering a component name from a single JSON Pointer token.
Use it anywhere a reference is split back into a name — renaming, pruning, or resolving a ref to its definition — or names containing "/" or "~" are corrupted. Order is the inverse of escaping: "~1" must be unescaped before "~0", or the "~" recovered from "~0" could combine with a following "1".
Mirrors unescapeJSONPointer in the parser's resolver, which has always implemented this for reference resolution.
Types ¶
type PathBuilder ¶
type PathBuilder struct {
// contains filtered or unexported fields
}
PathBuilder provides efficient incremental path construction. Uses push/pop semantics to avoid allocations during traversal. The full string is only materialized when String() is called.
func Get ¶
func Get() *PathBuilder
Get retrieves a PathBuilder from the pool, reset and ready to use.
func (*PathBuilder) Push ¶
func (p *PathBuilder) Push(segment string)
Push adds a segment to the path.
func (*PathBuilder) PushIndex ¶
func (p *PathBuilder) PushIndex(i int)
PushIndex adds an array index segment: "[0]", "[1]", etc.
func (*PathBuilder) String ¶
func (p *PathBuilder) String() string
String materializes the full path. Only call when the path is needed.