forked from getkin/kin-openapi
/
paths.go
99 lines (90 loc) · 2.26 KB
/
paths.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package openapi3
import (
"context"
"fmt"
"strings"
)
// Paths is specified by OpenAPI/Swagger standard version 3.0.
type Paths map[string]*PathItem
func (paths Paths) Validate(c context.Context) error {
normalizedPaths := make(map[string]string)
for path, pathItem := range paths {
normalizedPath := normalizePathKey(path)
if oldPath, exists := normalizedPaths[normalizedPath]; exists {
return fmt.Errorf("Conflicting paths '%v' and '%v'", path, oldPath)
}
if path == "" || path[0] != '/' {
return fmt.Errorf("Path '%v' does not start with '/'", path)
}
if strings.Contains(path, "//") {
return fmt.Errorf("Path '%v' contains '//'", path)
}
normalizedPaths[path] = path
if err := pathItem.Validate(c); err != nil {
return err
}
}
return nil
}
// Find returns a path that matches the key.
//
// The method ignores differences in template variable names (except possible "*" suffix).
//
// For example:
//
// paths := openapi3.Paths {
// "/person/{personName}": &openapi3.PathItem{},
// }
// pathItem := path.Find("/person/{name}")
//
// would return the correct path item.
func (paths Paths) Find(key string) *PathItem {
// Try directly access the map
pathItem := paths[key]
if pathItem != nil {
return pathItem
}
// Use normalized keys
normalizedSearchedPath := normalizePathKey(key)
for path, pathItem := range paths {
normalizedPath := normalizePathKey(path)
if normalizedPath == normalizedSearchedPath {
return pathItem
}
}
return nil
}
func normalizePathKey(key string) string {
// If the argument has no path variables, return the argument
if strings.IndexByte(key, '{') < 0 {
return key
}
// Allocate buffer
buf := make([]byte, 0, len(key))
// Visit each byte
isVariable := false
for i := 0; i < len(key); i++ {
c := key[i]
if isVariable {
if c == '}' {
// End path variables
// First append possible '*' before this character
// The character '}' will be appended
if i > 0 && key[i-1] == '*' {
buf = append(buf, '*')
}
isVariable = false
} else {
// Skip this character
continue
}
} else if c == '{' {
// Begin path variable
// The character '{' will be appended
isVariable = true
}
// Append the character
buf = append(buf, c)
}
return string(buf)
}