analyzer.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package analysis
  15. import (
  16. "fmt"
  17. slashpath "path"
  18. "strconv"
  19. "strings"
  20. "github.com/go-openapi/jsonpointer"
  21. "github.com/go-openapi/spec"
  22. "github.com/go-openapi/swag"
  23. )
  24. type referenceAnalysis struct {
  25. schemas map[string]spec.Ref
  26. responses map[string]spec.Ref
  27. parameters map[string]spec.Ref
  28. items map[string]spec.Ref
  29. headerItems map[string]spec.Ref
  30. parameterItems map[string]spec.Ref
  31. allRefs map[string]spec.Ref
  32. pathItems map[string]spec.Ref
  33. }
  34. func (r *referenceAnalysis) addRef(key string, ref spec.Ref) {
  35. r.allRefs["#"+key] = ref
  36. }
  37. func (r *referenceAnalysis) addItemsRef(key string, items *spec.Items, location string) {
  38. r.items["#"+key] = items.Ref
  39. r.addRef(key, items.Ref)
  40. if location == "header" {
  41. // NOTE: in swagger 2.0, headers and parameters (but not body param schemas) are simple schemas
  42. // and $ref are not supported here. However it is possible to analyze this.
  43. r.headerItems["#"+key] = items.Ref
  44. } else {
  45. r.parameterItems["#"+key] = items.Ref
  46. }
  47. }
  48. func (r *referenceAnalysis) addSchemaRef(key string, ref SchemaRef) {
  49. r.schemas["#"+key] = ref.Schema.Ref
  50. r.addRef(key, ref.Schema.Ref)
  51. }
  52. func (r *referenceAnalysis) addResponseRef(key string, resp *spec.Response) {
  53. r.responses["#"+key] = resp.Ref
  54. r.addRef(key, resp.Ref)
  55. }
  56. func (r *referenceAnalysis) addParamRef(key string, param *spec.Parameter) {
  57. r.parameters["#"+key] = param.Ref
  58. r.addRef(key, param.Ref)
  59. }
  60. func (r *referenceAnalysis) addPathItemRef(key string, pathItem *spec.PathItem) {
  61. r.pathItems["#"+key] = pathItem.Ref
  62. r.addRef(key, pathItem.Ref)
  63. }
  64. type patternAnalysis struct {
  65. parameters map[string]string
  66. headers map[string]string
  67. items map[string]string
  68. schemas map[string]string
  69. allPatterns map[string]string
  70. }
  71. func (p *patternAnalysis) addPattern(key, pattern string) {
  72. p.allPatterns["#"+key] = pattern
  73. }
  74. func (p *patternAnalysis) addParameterPattern(key, pattern string) {
  75. p.parameters["#"+key] = pattern
  76. p.addPattern(key, pattern)
  77. }
  78. func (p *patternAnalysis) addHeaderPattern(key, pattern string) {
  79. p.headers["#"+key] = pattern
  80. p.addPattern(key, pattern)
  81. }
  82. func (p *patternAnalysis) addItemsPattern(key, pattern string) {
  83. p.items["#"+key] = pattern
  84. p.addPattern(key, pattern)
  85. }
  86. func (p *patternAnalysis) addSchemaPattern(key, pattern string) {
  87. p.schemas["#"+key] = pattern
  88. p.addPattern(key, pattern)
  89. }
  90. // New takes a swagger spec object and returns an analyzed spec document.
  91. // The analyzed document contains a number of indices that make it easier to
  92. // reason about semantics of a swagger specification for use in code generation
  93. // or validation etc.
  94. func New(doc *spec.Swagger) *Spec {
  95. a := &Spec{
  96. spec: doc,
  97. consumes: make(map[string]struct{}, 150),
  98. produces: make(map[string]struct{}, 150),
  99. authSchemes: make(map[string]struct{}, 150),
  100. operations: make(map[string]map[string]*spec.Operation, 150),
  101. allSchemas: make(map[string]SchemaRef, 150),
  102. allOfs: make(map[string]SchemaRef, 150),
  103. references: referenceAnalysis{
  104. schemas: make(map[string]spec.Ref, 150),
  105. pathItems: make(map[string]spec.Ref, 150),
  106. responses: make(map[string]spec.Ref, 150),
  107. parameters: make(map[string]spec.Ref, 150),
  108. items: make(map[string]spec.Ref, 150),
  109. headerItems: make(map[string]spec.Ref, 150),
  110. parameterItems: make(map[string]spec.Ref, 150),
  111. allRefs: make(map[string]spec.Ref, 150),
  112. },
  113. patterns: patternAnalysis{
  114. parameters: make(map[string]string, 150),
  115. headers: make(map[string]string, 150),
  116. items: make(map[string]string, 150),
  117. schemas: make(map[string]string, 150),
  118. allPatterns: make(map[string]string, 150),
  119. },
  120. }
  121. a.initialize()
  122. return a
  123. }
  124. // Spec is an analyzed specification object. It takes a swagger spec object and turns it into a registry
  125. // with a bunch of utility methods to act on the information in the spec.
  126. type Spec struct {
  127. spec *spec.Swagger
  128. consumes map[string]struct{}
  129. produces map[string]struct{}
  130. authSchemes map[string]struct{}
  131. operations map[string]map[string]*spec.Operation
  132. references referenceAnalysis
  133. patterns patternAnalysis
  134. allSchemas map[string]SchemaRef
  135. allOfs map[string]SchemaRef
  136. }
  137. func (s *Spec) reset() {
  138. s.consumes = make(map[string]struct{}, 150)
  139. s.produces = make(map[string]struct{}, 150)
  140. s.authSchemes = make(map[string]struct{}, 150)
  141. s.operations = make(map[string]map[string]*spec.Operation, 150)
  142. s.allSchemas = make(map[string]SchemaRef, 150)
  143. s.allOfs = make(map[string]SchemaRef, 150)
  144. s.references.schemas = make(map[string]spec.Ref, 150)
  145. s.references.pathItems = make(map[string]spec.Ref, 150)
  146. s.references.responses = make(map[string]spec.Ref, 150)
  147. s.references.parameters = make(map[string]spec.Ref, 150)
  148. s.references.items = make(map[string]spec.Ref, 150)
  149. s.references.headerItems = make(map[string]spec.Ref, 150)
  150. s.references.parameterItems = make(map[string]spec.Ref, 150)
  151. s.references.allRefs = make(map[string]spec.Ref, 150)
  152. s.patterns.parameters = make(map[string]string, 150)
  153. s.patterns.headers = make(map[string]string, 150)
  154. s.patterns.items = make(map[string]string, 150)
  155. s.patterns.schemas = make(map[string]string, 150)
  156. s.patterns.allPatterns = make(map[string]string, 150)
  157. }
  158. func (s *Spec) reload() {
  159. s.reset()
  160. s.initialize()
  161. }
  162. func (s *Spec) initialize() {
  163. for _, c := range s.spec.Consumes {
  164. s.consumes[c] = struct{}{}
  165. }
  166. for _, c := range s.spec.Produces {
  167. s.produces[c] = struct{}{}
  168. }
  169. for _, ss := range s.spec.Security {
  170. for k := range ss {
  171. s.authSchemes[k] = struct{}{}
  172. }
  173. }
  174. for path, pathItem := range s.AllPaths() {
  175. s.analyzeOperations(path, &pathItem)
  176. }
  177. for name, parameter := range s.spec.Parameters {
  178. refPref := slashpath.Join("/parameters", jsonpointer.Escape(name))
  179. if parameter.Items != nil {
  180. s.analyzeItems("items", parameter.Items, refPref, "parameter")
  181. }
  182. if parameter.In == "body" && parameter.Schema != nil {
  183. s.analyzeSchema("schema", *parameter.Schema, refPref)
  184. }
  185. if parameter.Pattern != "" {
  186. s.patterns.addParameterPattern(refPref, parameter.Pattern)
  187. }
  188. }
  189. for name, response := range s.spec.Responses {
  190. refPref := slashpath.Join("/responses", jsonpointer.Escape(name))
  191. for k, v := range response.Headers {
  192. hRefPref := slashpath.Join(refPref, "headers", k)
  193. if v.Items != nil {
  194. s.analyzeItems("items", v.Items, hRefPref, "header")
  195. }
  196. if v.Pattern != "" {
  197. s.patterns.addHeaderPattern(hRefPref, v.Pattern)
  198. }
  199. }
  200. if response.Schema != nil {
  201. s.analyzeSchema("schema", *response.Schema, refPref)
  202. }
  203. }
  204. for name, schema := range s.spec.Definitions {
  205. s.analyzeSchema(name, schema, "/definitions")
  206. }
  207. // TODO: after analyzing all things and flattening schemas etc
  208. // resolve all the collected references to their final representations
  209. // best put in a separate method because this could get expensive
  210. }
  211. func (s *Spec) analyzeOperations(path string, pi *spec.PathItem) {
  212. // TODO: resolve refs here?
  213. // Currently, operations declared via pathItem $ref are known only after expansion
  214. op := pi
  215. if pi.Ref.String() != "" {
  216. key := slashpath.Join("/paths", jsonpointer.Escape(path))
  217. s.references.addPathItemRef(key, pi)
  218. }
  219. s.analyzeOperation("GET", path, op.Get)
  220. s.analyzeOperation("PUT", path, op.Put)
  221. s.analyzeOperation("POST", path, op.Post)
  222. s.analyzeOperation("PATCH", path, op.Patch)
  223. s.analyzeOperation("DELETE", path, op.Delete)
  224. s.analyzeOperation("HEAD", path, op.Head)
  225. s.analyzeOperation("OPTIONS", path, op.Options)
  226. for i, param := range op.Parameters {
  227. refPref := slashpath.Join("/paths", jsonpointer.Escape(path), "parameters", strconv.Itoa(i))
  228. if param.Ref.String() != "" {
  229. s.references.addParamRef(refPref, &param)
  230. }
  231. if param.Pattern != "" {
  232. s.patterns.addParameterPattern(refPref, param.Pattern)
  233. }
  234. if param.Items != nil {
  235. s.analyzeItems("items", param.Items, refPref, "parameter")
  236. }
  237. if param.Schema != nil {
  238. s.analyzeSchema("schema", *param.Schema, refPref)
  239. }
  240. }
  241. }
  242. func (s *Spec) analyzeItems(name string, items *spec.Items, prefix, location string) {
  243. if items == nil {
  244. return
  245. }
  246. refPref := slashpath.Join(prefix, name)
  247. s.analyzeItems(name, items.Items, refPref, location)
  248. if items.Ref.String() != "" {
  249. s.references.addItemsRef(refPref, items, location)
  250. }
  251. if items.Pattern != "" {
  252. s.patterns.addItemsPattern(refPref, items.Pattern)
  253. }
  254. }
  255. func (s *Spec) analyzeOperation(method, path string, op *spec.Operation) {
  256. if op == nil {
  257. return
  258. }
  259. for _, c := range op.Consumes {
  260. s.consumes[c] = struct{}{}
  261. }
  262. for _, c := range op.Produces {
  263. s.produces[c] = struct{}{}
  264. }
  265. for _, ss := range op.Security {
  266. for k := range ss {
  267. s.authSchemes[k] = struct{}{}
  268. }
  269. }
  270. if _, ok := s.operations[method]; !ok {
  271. s.operations[method] = make(map[string]*spec.Operation)
  272. }
  273. s.operations[method][path] = op
  274. prefix := slashpath.Join("/paths", jsonpointer.Escape(path), strings.ToLower(method))
  275. for i, param := range op.Parameters {
  276. refPref := slashpath.Join(prefix, "parameters", strconv.Itoa(i))
  277. if param.Ref.String() != "" {
  278. s.references.addParamRef(refPref, &param)
  279. }
  280. if param.Pattern != "" {
  281. s.patterns.addParameterPattern(refPref, param.Pattern)
  282. }
  283. s.analyzeItems("items", param.Items, refPref, "parameter")
  284. if param.In == "body" && param.Schema != nil {
  285. s.analyzeSchema("schema", *param.Schema, refPref)
  286. }
  287. }
  288. if op.Responses != nil {
  289. if op.Responses.Default != nil {
  290. refPref := slashpath.Join(prefix, "responses", "default")
  291. if op.Responses.Default.Ref.String() != "" {
  292. s.references.addResponseRef(refPref, op.Responses.Default)
  293. }
  294. for k, v := range op.Responses.Default.Headers {
  295. hRefPref := slashpath.Join(refPref, "headers", k)
  296. s.analyzeItems("items", v.Items, hRefPref, "header")
  297. if v.Pattern != "" {
  298. s.patterns.addHeaderPattern(hRefPref, v.Pattern)
  299. }
  300. }
  301. if op.Responses.Default.Schema != nil {
  302. s.analyzeSchema("schema", *op.Responses.Default.Schema, refPref)
  303. }
  304. }
  305. for k, res := range op.Responses.StatusCodeResponses {
  306. refPref := slashpath.Join(prefix, "responses", strconv.Itoa(k))
  307. if res.Ref.String() != "" {
  308. s.references.addResponseRef(refPref, &res)
  309. }
  310. for k, v := range res.Headers {
  311. hRefPref := slashpath.Join(refPref, "headers", k)
  312. s.analyzeItems("items", v.Items, hRefPref, "header")
  313. if v.Pattern != "" {
  314. s.patterns.addHeaderPattern(hRefPref, v.Pattern)
  315. }
  316. }
  317. if res.Schema != nil {
  318. s.analyzeSchema("schema", *res.Schema, refPref)
  319. }
  320. }
  321. }
  322. }
  323. func (s *Spec) analyzeSchema(name string, schema spec.Schema, prefix string) {
  324. refURI := slashpath.Join(prefix, jsonpointer.Escape(name))
  325. schRef := SchemaRef{
  326. Name: name,
  327. Schema: &schema,
  328. Ref: spec.MustCreateRef("#" + refURI),
  329. TopLevel: prefix == "/definitions",
  330. }
  331. s.allSchemas["#"+refURI] = schRef
  332. if schema.Ref.String() != "" {
  333. s.references.addSchemaRef(refURI, schRef)
  334. }
  335. if schema.Pattern != "" {
  336. s.patterns.addSchemaPattern(refURI, schema.Pattern)
  337. }
  338. for k, v := range schema.Definitions {
  339. s.analyzeSchema(k, v, slashpath.Join(refURI, "definitions"))
  340. }
  341. for k, v := range schema.Properties {
  342. s.analyzeSchema(k, v, slashpath.Join(refURI, "properties"))
  343. }
  344. for k, v := range schema.PatternProperties {
  345. // NOTE: swagger 2.0 does not support PatternProperties.
  346. // However it is possible to analyze this in a schema
  347. s.analyzeSchema(k, v, slashpath.Join(refURI, "patternProperties"))
  348. }
  349. for i, v := range schema.AllOf {
  350. s.analyzeSchema(strconv.Itoa(i), v, slashpath.Join(refURI, "allOf"))
  351. }
  352. if len(schema.AllOf) > 0 {
  353. s.allOfs["#"+refURI] = schRef
  354. }
  355. for i, v := range schema.AnyOf {
  356. // NOTE: swagger 2.0 does not support anyOf constructs.
  357. // However it is possible to analyze this in a schema
  358. s.analyzeSchema(strconv.Itoa(i), v, slashpath.Join(refURI, "anyOf"))
  359. }
  360. for i, v := range schema.OneOf {
  361. // NOTE: swagger 2.0 does not support oneOf constructs.
  362. // However it is possible to analyze this in a schema
  363. s.analyzeSchema(strconv.Itoa(i), v, slashpath.Join(refURI, "oneOf"))
  364. }
  365. if schema.Not != nil {
  366. // NOTE: swagger 2.0 does not support "not" constructs.
  367. // However it is possible to analyze this in a schema
  368. s.analyzeSchema("not", *schema.Not, refURI)
  369. }
  370. if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
  371. s.analyzeSchema("additionalProperties", *schema.AdditionalProperties.Schema, refURI)
  372. }
  373. if schema.AdditionalItems != nil && schema.AdditionalItems.Schema != nil {
  374. // NOTE: swagger 2.0 does not support AdditionalItems.
  375. // However it is possible to analyze this in a schema
  376. s.analyzeSchema("additionalItems", *schema.AdditionalItems.Schema, refURI)
  377. }
  378. if schema.Items != nil {
  379. if schema.Items.Schema != nil {
  380. s.analyzeSchema("items", *schema.Items.Schema, refURI)
  381. }
  382. for i, sch := range schema.Items.Schemas {
  383. s.analyzeSchema(strconv.Itoa(i), sch, slashpath.Join(refURI, "items"))
  384. }
  385. }
  386. }
  387. // SecurityRequirement is a representation of a security requirement for an operation
  388. type SecurityRequirement struct {
  389. Name string
  390. Scopes []string
  391. }
  392. // SecurityRequirementsFor gets the security requirements for the operation
  393. func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) [][]SecurityRequirement {
  394. if s.spec.Security == nil && operation.Security == nil {
  395. return nil
  396. }
  397. schemes := s.spec.Security
  398. if operation.Security != nil {
  399. schemes = operation.Security
  400. }
  401. result := [][]SecurityRequirement{}
  402. for _, scheme := range schemes {
  403. if len(scheme) == 0 {
  404. // append a zero object for anonymous
  405. result = append(result, []SecurityRequirement{{}})
  406. continue
  407. }
  408. var reqs []SecurityRequirement
  409. for k, v := range scheme {
  410. if v == nil {
  411. v = []string{}
  412. }
  413. reqs = append(reqs, SecurityRequirement{Name: k, Scopes: v})
  414. }
  415. result = append(result, reqs)
  416. }
  417. return result
  418. }
  419. // SecurityDefinitionsForRequirements gets the matching security definitions for a set of requirements
  420. func (s *Spec) SecurityDefinitionsForRequirements(requirements []SecurityRequirement) map[string]spec.SecurityScheme {
  421. result := make(map[string]spec.SecurityScheme)
  422. for _, v := range requirements {
  423. if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok {
  424. if definition != nil {
  425. result[v.Name] = *definition
  426. }
  427. }
  428. }
  429. return result
  430. }
  431. // SecurityDefinitionsFor gets the matching security definitions for a set of requirements
  432. func (s *Spec) SecurityDefinitionsFor(operation *spec.Operation) map[string]spec.SecurityScheme {
  433. requirements := s.SecurityRequirementsFor(operation)
  434. if len(requirements) == 0 {
  435. return nil
  436. }
  437. result := make(map[string]spec.SecurityScheme)
  438. for _, reqs := range requirements {
  439. for _, v := range reqs {
  440. if v.Name == "" {
  441. // optional requirement
  442. continue
  443. }
  444. if _, ok := result[v.Name]; ok {
  445. // duplicate requirement
  446. continue
  447. }
  448. if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok {
  449. if definition != nil {
  450. result[v.Name] = *definition
  451. }
  452. }
  453. }
  454. }
  455. return result
  456. }
  457. // ConsumesFor gets the mediatypes for the operation
  458. func (s *Spec) ConsumesFor(operation *spec.Operation) []string {
  459. if len(operation.Consumes) == 0 {
  460. cons := make(map[string]struct{}, len(s.spec.Consumes))
  461. for _, k := range s.spec.Consumes {
  462. cons[k] = struct{}{}
  463. }
  464. return s.structMapKeys(cons)
  465. }
  466. cons := make(map[string]struct{}, len(operation.Consumes))
  467. for _, c := range operation.Consumes {
  468. cons[c] = struct{}{}
  469. }
  470. return s.structMapKeys(cons)
  471. }
  472. // ProducesFor gets the mediatypes for the operation
  473. func (s *Spec) ProducesFor(operation *spec.Operation) []string {
  474. if len(operation.Produces) == 0 {
  475. prod := make(map[string]struct{}, len(s.spec.Produces))
  476. for _, k := range s.spec.Produces {
  477. prod[k] = struct{}{}
  478. }
  479. return s.structMapKeys(prod)
  480. }
  481. prod := make(map[string]struct{}, len(operation.Produces))
  482. for _, c := range operation.Produces {
  483. prod[c] = struct{}{}
  484. }
  485. return s.structMapKeys(prod)
  486. }
  487. func mapKeyFromParam(param *spec.Parameter) string {
  488. return fmt.Sprintf("%s#%s", param.In, fieldNameFromParam(param))
  489. }
  490. func fieldNameFromParam(param *spec.Parameter) string {
  491. // TODO: this should be x-go-name
  492. if nm, ok := param.Extensions.GetString("go-name"); ok {
  493. return nm
  494. }
  495. return swag.ToGoName(param.Name)
  496. }
  497. // ErrorOnParamFunc is a callback function to be invoked
  498. // whenever an error is encountered while resolving references
  499. // on parameters.
  500. //
  501. // This function takes as input the spec.Parameter which triggered the
  502. // error and the error itself.
  503. //
  504. // If the callback function returns false, the calling function should bail.
  505. //
  506. // If it returns true, the calling function should continue evaluating parameters.
  507. // A nil ErrorOnParamFunc must be evaluated as equivalent to panic().
  508. type ErrorOnParamFunc func(spec.Parameter, error) bool
  509. func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) {
  510. for _, param := range parameters {
  511. pr := param
  512. if pr.Ref.String() != "" {
  513. obj, _, err := pr.Ref.GetPointer().Get(s.spec)
  514. if err != nil {
  515. if callmeOnError != nil {
  516. if callmeOnError(param, fmt.Errorf("invalid reference: %q", pr.Ref.String())) {
  517. continue
  518. }
  519. break
  520. } else {
  521. panic(fmt.Sprintf("invalid reference: %q", pr.Ref.String()))
  522. }
  523. }
  524. if objAsParam, ok := obj.(spec.Parameter); ok {
  525. pr = objAsParam
  526. } else {
  527. if callmeOnError != nil {
  528. if callmeOnError(param, fmt.Errorf("resolved reference is not a parameter: %q", pr.Ref.String())) {
  529. continue
  530. }
  531. break
  532. } else {
  533. panic(fmt.Sprintf("resolved reference is not a parameter: %q", pr.Ref.String()))
  534. }
  535. }
  536. }
  537. res[mapKeyFromParam(&pr)] = pr
  538. }
  539. }
  540. // ParametersFor the specified operation id.
  541. //
  542. // Assumes parameters properly resolve references if any and that
  543. // such references actually resolve to a parameter object.
  544. // Otherwise, panics.
  545. func (s *Spec) ParametersFor(operationID string) []spec.Parameter {
  546. return s.SafeParametersFor(operationID, nil)
  547. }
  548. // SafeParametersFor the specified operation id.
  549. //
  550. // Does not assume parameters properly resolve references or that
  551. // such references actually resolve to a parameter object.
  552. //
  553. // Upon error, invoke a ErrorOnParamFunc callback with the erroneous
  554. // parameters. If the callback is set to nil, panics upon errors.
  555. func (s *Spec) SafeParametersFor(operationID string, callmeOnError ErrorOnParamFunc) []spec.Parameter {
  556. gatherParams := func(pi *spec.PathItem, op *spec.Operation) []spec.Parameter {
  557. bag := make(map[string]spec.Parameter)
  558. s.paramsAsMap(pi.Parameters, bag, callmeOnError)
  559. s.paramsAsMap(op.Parameters, bag, callmeOnError)
  560. var res []spec.Parameter
  561. for _, v := range bag {
  562. res = append(res, v)
  563. }
  564. return res
  565. }
  566. for _, pi := range s.spec.Paths.Paths {
  567. if pi.Get != nil && pi.Get.ID == operationID {
  568. return gatherParams(&pi, pi.Get)
  569. }
  570. if pi.Head != nil && pi.Head.ID == operationID {
  571. return gatherParams(&pi, pi.Head)
  572. }
  573. if pi.Options != nil && pi.Options.ID == operationID {
  574. return gatherParams(&pi, pi.Options)
  575. }
  576. if pi.Post != nil && pi.Post.ID == operationID {
  577. return gatherParams(&pi, pi.Post)
  578. }
  579. if pi.Patch != nil && pi.Patch.ID == operationID {
  580. return gatherParams(&pi, pi.Patch)
  581. }
  582. if pi.Put != nil && pi.Put.ID == operationID {
  583. return gatherParams(&pi, pi.Put)
  584. }
  585. if pi.Delete != nil && pi.Delete.ID == operationID {
  586. return gatherParams(&pi, pi.Delete)
  587. }
  588. }
  589. return nil
  590. }
  591. // ParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that
  592. // apply for the method and path.
  593. //
  594. // Assumes parameters properly resolve references if any and that
  595. // such references actually resolve to a parameter object.
  596. // Otherwise, panics.
  597. func (s *Spec) ParamsFor(method, path string) map[string]spec.Parameter {
  598. return s.SafeParamsFor(method, path, nil)
  599. }
  600. // SafeParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that
  601. // apply for the method and path.
  602. //
  603. // Does not assume parameters properly resolve references or that
  604. // such references actually resolve to a parameter object.
  605. //
  606. // Upon error, invoke a ErrorOnParamFunc callback with the erroneous
  607. // parameters. If the callback is set to nil, panics upon errors.
  608. func (s *Spec) SafeParamsFor(method, path string, callmeOnError ErrorOnParamFunc) map[string]spec.Parameter {
  609. res := make(map[string]spec.Parameter)
  610. if pi, ok := s.spec.Paths.Paths[path]; ok {
  611. s.paramsAsMap(pi.Parameters, res, callmeOnError)
  612. s.paramsAsMap(s.operations[strings.ToUpper(method)][path].Parameters, res, callmeOnError)
  613. }
  614. return res
  615. }
  616. // OperationForName gets the operation for the given id
  617. func (s *Spec) OperationForName(operationID string) (string, string, *spec.Operation, bool) {
  618. for method, pathItem := range s.operations {
  619. for path, op := range pathItem {
  620. if operationID == op.ID {
  621. return method, path, op, true
  622. }
  623. }
  624. }
  625. return "", "", nil, false
  626. }
  627. // OperationFor the given method and path
  628. func (s *Spec) OperationFor(method, path string) (*spec.Operation, bool) {
  629. if mp, ok := s.operations[strings.ToUpper(method)]; ok {
  630. op, fn := mp[path]
  631. return op, fn
  632. }
  633. return nil, false
  634. }
  635. // Operations gathers all the operations specified in the spec document
  636. func (s *Spec) Operations() map[string]map[string]*spec.Operation {
  637. return s.operations
  638. }
  639. func (s *Spec) structMapKeys(mp map[string]struct{}) []string {
  640. if len(mp) == 0 {
  641. return nil
  642. }
  643. result := make([]string, 0, len(mp))
  644. for k := range mp {
  645. result = append(result, k)
  646. }
  647. return result
  648. }
  649. // AllPaths returns all the paths in the swagger spec
  650. func (s *Spec) AllPaths() map[string]spec.PathItem {
  651. if s.spec == nil || s.spec.Paths == nil {
  652. return nil
  653. }
  654. return s.spec.Paths.Paths
  655. }
  656. // OperationIDs gets all the operation ids based on method an dpath
  657. func (s *Spec) OperationIDs() []string {
  658. if len(s.operations) == 0 {
  659. return nil
  660. }
  661. result := make([]string, 0, len(s.operations))
  662. for method, v := range s.operations {
  663. for p, o := range v {
  664. if o.ID != "" {
  665. result = append(result, o.ID)
  666. } else {
  667. result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p))
  668. }
  669. }
  670. }
  671. return result
  672. }
  673. // OperationMethodPaths gets all the operation ids based on method an dpath
  674. func (s *Spec) OperationMethodPaths() []string {
  675. if len(s.operations) == 0 {
  676. return nil
  677. }
  678. result := make([]string, 0, len(s.operations))
  679. for method, v := range s.operations {
  680. for p := range v {
  681. result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p))
  682. }
  683. }
  684. return result
  685. }
  686. // RequiredConsumes gets all the distinct consumes that are specified in the specification document
  687. func (s *Spec) RequiredConsumes() []string {
  688. return s.structMapKeys(s.consumes)
  689. }
  690. // RequiredProduces gets all the distinct produces that are specified in the specification document
  691. func (s *Spec) RequiredProduces() []string {
  692. return s.structMapKeys(s.produces)
  693. }
  694. // RequiredSecuritySchemes gets all the distinct security schemes that are specified in the swagger spec
  695. func (s *Spec) RequiredSecuritySchemes() []string {
  696. return s.structMapKeys(s.authSchemes)
  697. }
  698. // SchemaRef is a reference to a schema
  699. type SchemaRef struct {
  700. Name string
  701. Ref spec.Ref
  702. Schema *spec.Schema
  703. TopLevel bool
  704. }
  705. // SchemasWithAllOf returns schema references to all schemas that are defined
  706. // with an allOf key
  707. func (s *Spec) SchemasWithAllOf() (result []SchemaRef) {
  708. for _, v := range s.allOfs {
  709. result = append(result, v)
  710. }
  711. return
  712. }
  713. // AllDefinitions returns schema references for all the definitions that were discovered
  714. func (s *Spec) AllDefinitions() (result []SchemaRef) {
  715. for _, v := range s.allSchemas {
  716. result = append(result, v)
  717. }
  718. return
  719. }
  720. // AllDefinitionReferences returns json refs for all the discovered schemas
  721. func (s *Spec) AllDefinitionReferences() (result []string) {
  722. for _, v := range s.references.schemas {
  723. result = append(result, v.String())
  724. }
  725. return
  726. }
  727. // AllParameterReferences returns json refs for all the discovered parameters
  728. func (s *Spec) AllParameterReferences() (result []string) {
  729. for _, v := range s.references.parameters {
  730. result = append(result, v.String())
  731. }
  732. return
  733. }
  734. // AllResponseReferences returns json refs for all the discovered responses
  735. func (s *Spec) AllResponseReferences() (result []string) {
  736. for _, v := range s.references.responses {
  737. result = append(result, v.String())
  738. }
  739. return
  740. }
  741. // AllPathItemReferences returns the references for all the items
  742. func (s *Spec) AllPathItemReferences() (result []string) {
  743. for _, v := range s.references.pathItems {
  744. result = append(result, v.String())
  745. }
  746. return
  747. }
  748. // AllItemsReferences returns the references for all the items in simple schemas (parameters or headers).
  749. //
  750. // NOTE: since Swagger 2.0 forbids $ref in simple params, this should always yield an empty slice for a valid
  751. // Swagger 2.0 spec.
  752. func (s *Spec) AllItemsReferences() (result []string) {
  753. for _, v := range s.references.items {
  754. result = append(result, v.String())
  755. }
  756. return
  757. }
  758. // AllReferences returns all the references found in the document, with possible duplicates
  759. func (s *Spec) AllReferences() (result []string) {
  760. for _, v := range s.references.allRefs {
  761. result = append(result, v.String())
  762. }
  763. return
  764. }
  765. // AllRefs returns all the unique references found in the document
  766. func (s *Spec) AllRefs() (result []spec.Ref) {
  767. set := make(map[string]struct{})
  768. for _, v := range s.references.allRefs {
  769. a := v.String()
  770. if a == "" {
  771. continue
  772. }
  773. if _, ok := set[a]; !ok {
  774. set[a] = struct{}{}
  775. result = append(result, v)
  776. }
  777. }
  778. return
  779. }
  780. func cloneStringMap(source map[string]string) map[string]string {
  781. res := make(map[string]string, len(source))
  782. for k, v := range source {
  783. res[k] = v
  784. }
  785. return res
  786. }
  787. // ParameterPatterns returns all the patterns found in parameters
  788. // the map is cloned to avoid accidental changes
  789. func (s *Spec) ParameterPatterns() map[string]string {
  790. return cloneStringMap(s.patterns.parameters)
  791. }
  792. // HeaderPatterns returns all the patterns found in response headers
  793. // the map is cloned to avoid accidental changes
  794. func (s *Spec) HeaderPatterns() map[string]string {
  795. return cloneStringMap(s.patterns.headers)
  796. }
  797. // ItemsPatterns returns all the patterns found in simple array items
  798. // the map is cloned to avoid accidental changes
  799. func (s *Spec) ItemsPatterns() map[string]string {
  800. return cloneStringMap(s.patterns.items)
  801. }
  802. // SchemaPatterns returns all the patterns found in schemas
  803. // the map is cloned to avoid accidental changes
  804. func (s *Spec) SchemaPatterns() map[string]string {
  805. return cloneStringMap(s.patterns.schemas)
  806. }
  807. // AllPatterns returns all the patterns found in the spec
  808. // the map is cloned to avoid accidental changes
  809. func (s *Spec) AllPatterns() map[string]string {
  810. return cloneStringMap(s.patterns.allPatterns)
  811. }