...

Source file src/github.com/go-openapi/spec/parameter.go

Documentation: github.com/go-openapi/spec

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

View as plain text