1 // Copyright 2015 go-swagger maintainers
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
23 "github.com/go-openapi/jsonpointer"
24 "github.com/go-openapi/swag"
28 //gob.Register(map[string][]interface{}{})
29 gob.Register(map[string]interface{}{})
30 gob.Register([]interface{}{})
33 // OperationProps describes an operation
36 // - schemes, when present must be from [http, https, ws, wss]: see validate
37 // - Security is handled as a special case: see MarshalJSON function
38 type OperationProps struct {
39 Description string `json:"description,omitempty"`
40 Consumes []string `json:"consumes,omitempty"`
41 Produces []string `json:"produces,omitempty"`
42 Schemes []string `json:"schemes,omitempty"`
43 Tags []string `json:"tags,omitempty"`
44 Summary string `json:"summary,omitempty"`
45 ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
46 ID string `json:"operationId,omitempty"`
47 Deprecated bool `json:"deprecated,omitempty"`
48 Security []map[string][]string `json:"security,omitempty"`
49 Parameters []Parameter `json:"parameters,omitempty"`
50 Responses *Responses `json:"responses,omitempty"`
53 // MarshalJSON takes care of serializing operation properties to JSON
55 // We use a custom marhaller here to handle a special cases related to
56 // the Security field. We need to preserve zero length slice
57 // while omitting the field when the value is nil/unset.
58 func (op OperationProps) MarshalJSON() ([]byte, error) {
59 type Alias OperationProps
60 if op.Security == nil {
61 return json.Marshal(&struct {
62 Security []map[string][]string `json:"security,omitempty"`
65 Security: op.Security,
69 return json.Marshal(&struct {
70 Security []map[string][]string `json:"security"`
73 Security: op.Security,
78 // Operation describes a single API operation on a path.
80 // For more information: http://goo.gl/8us55a#operationObject
81 type Operation struct {
86 // SuccessResponse gets a success response model
87 func (o *Operation) SuccessResponse() (*Response, int, bool) {
88 if o.Responses == nil {
92 responseCodes := make([]int, 0, len(o.Responses.StatusCodeResponses))
93 for k := range o.Responses.StatusCodeResponses {
94 if k >= 200 && k < 300 {
95 responseCodes = append(responseCodes, k)
98 if len(responseCodes) > 0 {
99 sort.Ints(responseCodes)
100 v := o.Responses.StatusCodeResponses[responseCodes[0]]
101 return &v, responseCodes[0], true
104 return o.Responses.Default, 0, false
107 // JSONLookup look up a value by the json property name
108 func (o Operation) JSONLookup(token string) (interface{}, error) {
109 if ex, ok := o.Extensions[token]; ok {
112 r, _, err := jsonpointer.GetForToken(o.OperationProps, token)
116 // UnmarshalJSON hydrates this items instance with the data from JSON
117 func (o *Operation) UnmarshalJSON(data []byte) error {
118 if err := json.Unmarshal(data, &o.OperationProps); err != nil {
121 return json.Unmarshal(data, &o.VendorExtensible)
124 // MarshalJSON converts this items object to JSON
125 func (o Operation) MarshalJSON() ([]byte, error) {
126 b1, err := json.Marshal(o.OperationProps)
130 b2, err := json.Marshal(o.VendorExtensible)
134 concated := swag.ConcatJSON(b1, b2)
138 // NewOperation creates a new operation instance.
139 // It expects an ID as parameter but not passing an ID is also valid.
140 func NewOperation(id string) *Operation {
146 // WithID sets the ID property on this operation, allows for chaining.
147 func (o *Operation) WithID(id string) *Operation {
152 // WithDescription sets the description on this operation, allows for chaining
153 func (o *Operation) WithDescription(description string) *Operation {
154 o.Description = description
158 // WithSummary sets the summary on this operation, allows for chaining
159 func (o *Operation) WithSummary(summary string) *Operation {
164 // WithExternalDocs sets/removes the external docs for/from this operation.
165 // When you pass empty strings as params the external documents will be removed.
166 // When you pass non-empty string as one value then those values will be used on the external docs object.
167 // So when you pass a non-empty description, you should also pass the url and vice versa.
168 func (o *Operation) WithExternalDocs(description, url string) *Operation {
169 if description == "" && url == "" {
174 if o.ExternalDocs == nil {
175 o.ExternalDocs = &ExternalDocumentation{}
177 o.ExternalDocs.Description = description
178 o.ExternalDocs.URL = url
182 // Deprecate marks the operation as deprecated
183 func (o *Operation) Deprecate() *Operation {
188 // Undeprecate marks the operation as not deprected
189 func (o *Operation) Undeprecate() *Operation {
194 // WithConsumes adds media types for incoming body values
195 func (o *Operation) WithConsumes(mediaTypes ...string) *Operation {
196 o.Consumes = append(o.Consumes, mediaTypes...)
200 // WithProduces adds media types for outgoing body values
201 func (o *Operation) WithProduces(mediaTypes ...string) *Operation {
202 o.Produces = append(o.Produces, mediaTypes...)
206 // WithTags adds tags for this operation
207 func (o *Operation) WithTags(tags ...string) *Operation {
208 o.Tags = append(o.Tags, tags...)
212 // AddParam adds a parameter to this operation, when a parameter for that location
213 // and with that name already exists it will be replaced
214 func (o *Operation) AddParam(param *Parameter) *Operation {
219 for i, p := range o.Parameters {
220 if p.Name == param.Name && p.In == param.In {
221 params := append(o.Parameters[:i], *param)
222 params = append(params, o.Parameters[i+1:]...)
223 o.Parameters = params
228 o.Parameters = append(o.Parameters, *param)
232 // RemoveParam removes a parameter from the operation
233 func (o *Operation) RemoveParam(name, in string) *Operation {
234 for i, p := range o.Parameters {
235 if p.Name == name && p.In == in {
236 o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...)
243 // SecuredWith adds a security scope to this operation.
244 func (o *Operation) SecuredWith(name string, scopes ...string) *Operation {
245 o.Security = append(o.Security, map[string][]string{name: scopes})
249 // WithDefaultResponse adds a default response to the operation.
250 // Passing a nil value will remove the response
251 func (o *Operation) WithDefaultResponse(response *Response) *Operation {
252 return o.RespondsWith(0, response)
255 // RespondsWith adds a status code response to the operation.
256 // When the code is 0 the value of the response will be used as default response value.
257 // When the value of the response is nil it will be removed from the operation
258 func (o *Operation) RespondsWith(code int, response *Response) *Operation {
259 if o.Responses == nil {
260 o.Responses = new(Responses)
263 o.Responses.Default = response
267 delete(o.Responses.StatusCodeResponses, code)
270 if o.Responses.StatusCodeResponses == nil {
271 o.Responses.StatusCodeResponses = make(map[int]Response)
273 o.Responses.StatusCodeResponses[code] = *response
277 type opsAlias OperationProps
279 type gobAlias struct {
280 Security []map[string]struct {
288 // GobEncode provides a safe gob encoder for Operation, including empty security requirements
289 func (o Operation) GobEncode() ([]byte, error) {
294 Ext: o.VendorExtensible,
295 Props: o.OperationProps,
298 err := gob.NewEncoder(&b).Encode(raw)
299 return b.Bytes(), err
302 // GobDecode provides a safe gob decoder for Operation, including empty security requirements
303 func (o *Operation) GobDecode(b []byte) error {
309 buf := bytes.NewBuffer(b)
310 err := gob.NewDecoder(buf).Decode(&raw)
314 o.VendorExtensible = raw.Ext
315 o.OperationProps = raw.Props
319 // GobEncode provides a safe gob encoder for Operation, including empty security requirements
320 func (op OperationProps) GobEncode() ([]byte, error) {
322 Alias: (*opsAlias)(&op),
326 if op.Security == nil {
327 // nil security requirement
328 err := gob.NewEncoder(&b).Encode(raw)
329 return b.Bytes(), err
332 if len(op.Security) == 0 {
333 // empty, but non-nil security requirement
334 raw.SecurityIsEmpty = true
335 raw.Alias.Security = nil
336 err := gob.NewEncoder(&b).Encode(raw)
337 return b.Bytes(), err
340 raw.Security = make([]map[string]struct {
343 }, 0, len(op.Security))
344 for _, req := range op.Security {
345 v := make(map[string]struct {
349 for k, val := range req {
357 raw.Security = append(raw.Security, v)
360 err := gob.NewEncoder(&b).Encode(raw)
361 return b.Bytes(), err
364 // GobDecode provides a safe gob decoder for Operation, including empty security requirements
365 func (op *OperationProps) GobDecode(b []byte) error {
368 buf := bytes.NewBuffer(b)
369 err := gob.NewDecoder(buf).Decode(&raw)
373 if raw.Alias == nil {
378 case raw.SecurityIsEmpty:
379 // empty, but non-nil security requirement
380 raw.Alias.Security = []map[string][]string{}
381 case len(raw.Alias.Security) == 0:
382 // nil security requirement
383 raw.Alias.Security = nil
385 raw.Alias.Security = make([]map[string][]string, 0, len(raw.Security))
386 for _, req := range raw.Security {
387 v := make(map[string][]string, len(req))
388 for k, val := range req {
389 v[k] = make([]string, 0, len(val.List))
390 v[k] = append(v[k], val.List...)
392 raw.Alias.Security = append(raw.Alias.Security, v)
396 *op = *(*OperationProps)(raw.Alias)