parameter.go 10 KB

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