本站源代码
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

322 lines
10KB

  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 spec
  15. import (
  16. "encoding/json"
  17. "strings"
  18. "github.com/go-openapi/jsonpointer"
  19. "github.com/go-openapi/swag"
  20. )
  21. // QueryParam creates a query parameter
  22. func QueryParam(name string) *Parameter {
  23. return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}}
  24. }
  25. // HeaderParam creates a header parameter, this is always required by default
  26. func HeaderParam(name string) *Parameter {
  27. return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}}
  28. }
  29. // PathParam creates a path parameter, this is always required
  30. func PathParam(name string) *Parameter {
  31. return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}}
  32. }
  33. // BodyParam creates a body parameter
  34. func BodyParam(name string, schema *Schema) *Parameter {
  35. return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema},
  36. SimpleSchema: SimpleSchema{Type: "object"}}
  37. }
  38. // FormDataParam creates a body parameter
  39. func FormDataParam(name string) *Parameter {
  40. return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}}
  41. }
  42. // FileParam creates a body parameter
  43. func FileParam(name string) *Parameter {
  44. return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"},
  45. SimpleSchema: SimpleSchema{Type: "file"}}
  46. }
  47. // SimpleArrayParam creates a param for a simple array (string, int, date etc)
  48. func SimpleArrayParam(name, tpe, fmt string) *Parameter {
  49. return &Parameter{ParamProps: ParamProps{Name: name},
  50. SimpleSchema: SimpleSchema{Type: jsonArray, CollectionFormat: "csv",
  51. Items: &Items{SimpleSchema: SimpleSchema{Type: "string", Format: fmt}}}}
  52. }
  53. // ParamRef creates a parameter that's a json reference
  54. func ParamRef(uri string) *Parameter {
  55. p := new(Parameter)
  56. p.Ref = MustCreateRef(uri)
  57. return p
  58. }
  59. // ParamProps describes the specific attributes of an operation parameter
  60. //
  61. // NOTE:
  62. // - Schema is defined when "in" == "body": see validate
  63. // - AllowEmptyValue is allowed where "in" == "query" || "formData"
  64. type ParamProps struct {
  65. Description string `json:"description,omitempty"`
  66. Name string `json:"name,omitempty"`
  67. In string `json:"in,omitempty"`
  68. Required bool `json:"required,omitempty"`
  69. Schema *Schema `json:"schema,omitempty"`
  70. AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
  71. }
  72. // Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn).
  73. //
  74. // There are five possible parameter types.
  75. // * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part
  76. // of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`,
  77. // the path parameter is `itemId`.
  78. // * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`.
  79. // * Header - Custom headers that are expected as part of the request.
  80. // * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be
  81. // _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for
  82. // documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist
  83. // together for the same operation.
  84. // * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or
  85. // `multipart/form-data` are used as the content type of the request (in Swagger's definition,
  86. // the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used
  87. // to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be
  88. // declared together with a body parameter for the same operation. Form parameters have a different format based on
  89. // the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4).
  90. // * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload.
  91. // For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple
  92. // parameters that are being transferred.
  93. // * `multipart/form-data` - each parameter takes a section in the payload with an internal header.
  94. // For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is
  95. // `submit-name`. This type of form parameters is more commonly used for file transfers.
  96. //
  97. // For more information: http://goo.gl/8us55a#parameterObject
  98. type Parameter struct {
  99. Refable
  100. CommonValidations
  101. SimpleSchema
  102. VendorExtensible
  103. ParamProps
  104. }
  105. // JSONLookup look up a value by the json property name
  106. func (p Parameter) JSONLookup(token string) (interface{}, error) {
  107. if ex, ok := p.Extensions[token]; ok {
  108. return &ex, nil
  109. }
  110. if token == jsonRef {
  111. return &p.Ref, nil
  112. }
  113. r, _, err := jsonpointer.GetForToken(p.CommonValidations, token)
  114. if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
  115. return nil, err
  116. }
  117. if r != nil {
  118. return r, nil
  119. }
  120. r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token)
  121. if err != nil && !strings.HasPrefix(err.Error(), "object has no field") {
  122. return nil, err
  123. }
  124. if r != nil {
  125. return r, nil
  126. }
  127. r, _, err = jsonpointer.GetForToken(p.ParamProps, token)
  128. return r, err
  129. }
  130. // WithDescription a fluent builder method for the description of the parameter
  131. func (p *Parameter) WithDescription(description string) *Parameter {
  132. p.Description = description
  133. return p
  134. }
  135. // Named a fluent builder method to override the name of the parameter
  136. func (p *Parameter) Named(name string) *Parameter {
  137. p.Name = name
  138. return p
  139. }
  140. // WithLocation a fluent builder method to override the location of the parameter
  141. func (p *Parameter) WithLocation(in string) *Parameter {
  142. p.In = in
  143. return p
  144. }
  145. // Typed a fluent builder method for the type of the parameter value
  146. func (p *Parameter) Typed(tpe, format string) *Parameter {
  147. p.Type = tpe
  148. p.Format = format
  149. return p
  150. }
  151. // CollectionOf a fluent builder method for an array parameter
  152. func (p *Parameter) CollectionOf(items *Items, format string) *Parameter {
  153. p.Type = jsonArray
  154. p.Items = items
  155. p.CollectionFormat = format
  156. return p
  157. }
  158. // WithDefault sets the default value on this parameter
  159. func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter {
  160. p.AsOptional() // with default implies optional
  161. p.Default = defaultValue
  162. return p
  163. }
  164. // AllowsEmptyValues flags this parameter as being ok with empty values
  165. func (p *Parameter) AllowsEmptyValues() *Parameter {
  166. p.AllowEmptyValue = true
  167. return p
  168. }
  169. // NoEmptyValues flags this parameter as not liking empty values
  170. func (p *Parameter) NoEmptyValues() *Parameter {
  171. p.AllowEmptyValue = false
  172. return p
  173. }
  174. // AsOptional flags this parameter as optional
  175. func (p *Parameter) AsOptional() *Parameter {
  176. p.Required = false
  177. return p
  178. }
  179. // AsRequired flags this parameter as required
  180. func (p *Parameter) AsRequired() *Parameter {
  181. if p.Default != nil { // with a default required makes no sense
  182. return p
  183. }
  184. p.Required = true
  185. return p
  186. }
  187. // WithMaxLength sets a max length value
  188. func (p *Parameter) WithMaxLength(max int64) *Parameter {
  189. p.MaxLength = &max
  190. return p
  191. }
  192. // WithMinLength sets a min length value
  193. func (p *Parameter) WithMinLength(min int64) *Parameter {
  194. p.MinLength = &min
  195. return p
  196. }
  197. // WithPattern sets a pattern value
  198. func (p *Parameter) WithPattern(pattern string) *Parameter {
  199. p.Pattern = pattern
  200. return p
  201. }
  202. // WithMultipleOf sets a multiple of value
  203. func (p *Parameter) WithMultipleOf(number float64) *Parameter {
  204. p.MultipleOf = &number
  205. return p
  206. }
  207. // WithMaximum sets a maximum number value
  208. func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter {
  209. p.Maximum = &max
  210. p.ExclusiveMaximum = exclusive
  211. return p
  212. }
  213. // WithMinimum sets a minimum number value
  214. func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter {
  215. p.Minimum = &min
  216. p.ExclusiveMinimum = exclusive
  217. return p
  218. }
  219. // WithEnum sets a the enum values (replace)
  220. func (p *Parameter) WithEnum(values ...interface{}) *Parameter {
  221. p.Enum = append([]interface{}{}, values...)
  222. return p
  223. }
  224. // WithMaxItems sets the max items
  225. func (p *Parameter) WithMaxItems(size int64) *Parameter {
  226. p.MaxItems = &size
  227. return p
  228. }
  229. // WithMinItems sets the min items
  230. func (p *Parameter) WithMinItems(size int64) *Parameter {
  231. p.MinItems = &size
  232. return p
  233. }
  234. // UniqueValues dictates that this array can only have unique items
  235. func (p *Parameter) UniqueValues() *Parameter {
  236. p.UniqueItems = true
  237. return p
  238. }
  239. // AllowDuplicates this array can have duplicates
  240. func (p *Parameter) AllowDuplicates() *Parameter {
  241. p.UniqueItems = false
  242. return p
  243. }
  244. // UnmarshalJSON hydrates this items instance with the data from JSON
  245. func (p *Parameter) UnmarshalJSON(data []byte) error {
  246. if err := json.Unmarshal(data, &p.CommonValidations); err != nil {
  247. return err
  248. }
  249. if err := json.Unmarshal(data, &p.Refable); err != nil {
  250. return err
  251. }
  252. if err := json.Unmarshal(data, &p.SimpleSchema); err != nil {
  253. return err
  254. }
  255. if err := json.Unmarshal(data, &p.VendorExtensible); err != nil {
  256. return err
  257. }
  258. return json.Unmarshal(data, &p.ParamProps)
  259. }
  260. // MarshalJSON converts this items object to JSON
  261. func (p Parameter) MarshalJSON() ([]byte, error) {
  262. b1, err := json.Marshal(p.CommonValidations)
  263. if err != nil {
  264. return nil, err
  265. }
  266. b2, err := json.Marshal(p.SimpleSchema)
  267. if err != nil {
  268. return nil, err
  269. }
  270. b3, err := json.Marshal(p.Refable)
  271. if err != nil {
  272. return nil, err
  273. }
  274. b4, err := json.Marshal(p.VendorExtensible)
  275. if err != nil {
  276. return nil, err
  277. }
  278. b5, err := json.Marshal(p.ParamProps)
  279. if err != nil {
  280. return nil, err
  281. }
  282. return swag.ConcatJSON(b3, b1, b2, b4, b5), nil
  283. }
上海开阖软件有限公司 沪ICP备12045867号-1