podman
397 строк · 10.8 Кб
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
15package spec16
17import (18"bytes"19"encoding/gob"20"encoding/json"21"sort"22
23"github.com/go-openapi/jsonpointer"24"github.com/go-openapi/swag"25)
26
27func init() {28gob.Register(map[string]interface{}{})29gob.Register([]interface{}{})30}
31
32// OperationProps describes an operation
33//
34// NOTES:
35// - schemes, when present must be from [http, https, ws, wss]: see validate
36// - Security is handled as a special case: see MarshalJSON function
37type OperationProps struct {38Description string `json:"description,omitempty"`39Consumes []string `json:"consumes,omitempty"`40Produces []string `json:"produces,omitempty"`41Schemes []string `json:"schemes,omitempty"`42Tags []string `json:"tags,omitempty"`43Summary string `json:"summary,omitempty"`44ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`45ID string `json:"operationId,omitempty"`46Deprecated bool `json:"deprecated,omitempty"`47Security []map[string][]string `json:"security,omitempty"`48Parameters []Parameter `json:"parameters,omitempty"`49Responses *Responses `json:"responses,omitempty"`50}
51
52// MarshalJSON takes care of serializing operation properties to JSON
53//
54// We use a custom marhaller here to handle a special cases related to
55// the Security field. We need to preserve zero length slice
56// while omitting the field when the value is nil/unset.
57func (op OperationProps) MarshalJSON() ([]byte, error) {58type Alias OperationProps59if op.Security == nil {60return json.Marshal(&struct {61Security []map[string][]string `json:"security,omitempty"`62*Alias63}{64Security: op.Security,65Alias: (*Alias)(&op),66})67}68return json.Marshal(&struct {69Security []map[string][]string `json:"security"`70*Alias71}{72Security: op.Security,73Alias: (*Alias)(&op),74})75}
76
77// Operation describes a single API operation on a path.
78//
79// For more information: http://goo.gl/8us55a#operationObject
80type Operation struct {81VendorExtensible
82OperationProps
83}
84
85// SuccessResponse gets a success response model
86func (o *Operation) SuccessResponse() (*Response, int, bool) {87if o.Responses == nil {88return nil, 0, false89}90
91responseCodes := make([]int, 0, len(o.Responses.StatusCodeResponses))92for k := range o.Responses.StatusCodeResponses {93if k >= 200 && k < 300 {94responseCodes = append(responseCodes, k)95}96}97if len(responseCodes) > 0 {98sort.Ints(responseCodes)99v := o.Responses.StatusCodeResponses[responseCodes[0]]100return &v, responseCodes[0], true101}102
103return o.Responses.Default, 0, false104}
105
106// JSONLookup look up a value by the json property name
107func (o Operation) JSONLookup(token string) (interface{}, error) {108if ex, ok := o.Extensions[token]; ok {109return &ex, nil110}111r, _, err := jsonpointer.GetForToken(o.OperationProps, token)112return r, err113}
114
115// UnmarshalJSON hydrates this items instance with the data from JSON
116func (o *Operation) UnmarshalJSON(data []byte) error {117if err := json.Unmarshal(data, &o.OperationProps); err != nil {118return err119}120return json.Unmarshal(data, &o.VendorExtensible)121}
122
123// MarshalJSON converts this items object to JSON
124func (o Operation) MarshalJSON() ([]byte, error) {125b1, err := json.Marshal(o.OperationProps)126if err != nil {127return nil, err128}129b2, err := json.Marshal(o.VendorExtensible)130if err != nil {131return nil, err132}133concated := swag.ConcatJSON(b1, b2)134return concated, nil135}
136
137// NewOperation creates a new operation instance.
138// It expects an ID as parameter but not passing an ID is also valid.
139func NewOperation(id string) *Operation {140op := new(Operation)141op.ID = id142return op143}
144
145// WithID sets the ID property on this operation, allows for chaining.
146func (o *Operation) WithID(id string) *Operation {147o.ID = id148return o149}
150
151// WithDescription sets the description on this operation, allows for chaining
152func (o *Operation) WithDescription(description string) *Operation {153o.Description = description154return o155}
156
157// WithSummary sets the summary on this operation, allows for chaining
158func (o *Operation) WithSummary(summary string) *Operation {159o.Summary = summary160return o161}
162
163// WithExternalDocs sets/removes the external docs for/from this operation.
164// When you pass empty strings as params the external documents will be removed.
165// When you pass non-empty string as one value then those values will be used on the external docs object.
166// So when you pass a non-empty description, you should also pass the url and vice versa.
167func (o *Operation) WithExternalDocs(description, url string) *Operation {168if description == "" && url == "" {169o.ExternalDocs = nil170return o171}172
173if o.ExternalDocs == nil {174o.ExternalDocs = &ExternalDocumentation{}175}176o.ExternalDocs.Description = description177o.ExternalDocs.URL = url178return o179}
180
181// Deprecate marks the operation as deprecated
182func (o *Operation) Deprecate() *Operation {183o.Deprecated = true184return o185}
186
187// Undeprecate marks the operation as not deprected
188func (o *Operation) Undeprecate() *Operation {189o.Deprecated = false190return o191}
192
193// WithConsumes adds media types for incoming body values
194func (o *Operation) WithConsumes(mediaTypes ...string) *Operation {195o.Consumes = append(o.Consumes, mediaTypes...)196return o197}
198
199// WithProduces adds media types for outgoing body values
200func (o *Operation) WithProduces(mediaTypes ...string) *Operation {201o.Produces = append(o.Produces, mediaTypes...)202return o203}
204
205// WithTags adds tags for this operation
206func (o *Operation) WithTags(tags ...string) *Operation {207o.Tags = append(o.Tags, tags...)208return o209}
210
211// AddParam adds a parameter to this operation, when a parameter for that location
212// and with that name already exists it will be replaced
213func (o *Operation) AddParam(param *Parameter) *Operation {214if param == nil {215return o216}217
218for i, p := range o.Parameters {219if p.Name == param.Name && p.In == param.In {220params := append(o.Parameters[:i], *param)221params = append(params, o.Parameters[i+1:]...)222o.Parameters = params223return o224}225}226
227o.Parameters = append(o.Parameters, *param)228return o229}
230
231// RemoveParam removes a parameter from the operation
232func (o *Operation) RemoveParam(name, in string) *Operation {233for i, p := range o.Parameters {234if p.Name == name && p.In == in {235o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...)236return o237}238}239return o240}
241
242// SecuredWith adds a security scope to this operation.
243func (o *Operation) SecuredWith(name string, scopes ...string) *Operation {244o.Security = append(o.Security, map[string][]string{name: scopes})245return o246}
247
248// WithDefaultResponse adds a default response to the operation.
249// Passing a nil value will remove the response
250func (o *Operation) WithDefaultResponse(response *Response) *Operation {251return o.RespondsWith(0, response)252}
253
254// RespondsWith adds a status code response to the operation.
255// When the code is 0 the value of the response will be used as default response value.
256// When the value of the response is nil it will be removed from the operation
257func (o *Operation) RespondsWith(code int, response *Response) *Operation {258if o.Responses == nil {259o.Responses = new(Responses)260}261if code == 0 {262o.Responses.Default = response263return o264}265if response == nil {266delete(o.Responses.StatusCodeResponses, code)267return o268}269if o.Responses.StatusCodeResponses == nil {270o.Responses.StatusCodeResponses = make(map[int]Response)271}272o.Responses.StatusCodeResponses[code] = *response273return o274}
275
276type opsAlias OperationProps277
278type gobAlias struct {279Security []map[string]struct {280List []string281Pad bool282}283Alias *opsAlias284SecurityIsEmpty bool285}
286
287// GobEncode provides a safe gob encoder for Operation, including empty security requirements
288func (o Operation) GobEncode() ([]byte, error) {289raw := struct {290Ext VendorExtensible
291Props OperationProps
292}{293Ext: o.VendorExtensible,294Props: o.OperationProps,295}296var b bytes.Buffer297err := gob.NewEncoder(&b).Encode(raw)298return b.Bytes(), err299}
300
301// GobDecode provides a safe gob decoder for Operation, including empty security requirements
302func (o *Operation) GobDecode(b []byte) error {303var raw struct {304Ext VendorExtensible
305Props OperationProps
306}307
308buf := bytes.NewBuffer(b)309err := gob.NewDecoder(buf).Decode(&raw)310if err != nil {311return err312}313o.VendorExtensible = raw.Ext314o.OperationProps = raw.Props315return nil316}
317
318// GobEncode provides a safe gob encoder for Operation, including empty security requirements
319func (op OperationProps) GobEncode() ([]byte, error) {320raw := gobAlias{321Alias: (*opsAlias)(&op),322}323
324var b bytes.Buffer325if op.Security == nil {326// nil security requirement327err := gob.NewEncoder(&b).Encode(raw)328return b.Bytes(), err329}330
331if len(op.Security) == 0 {332// empty, but non-nil security requirement333raw.SecurityIsEmpty = true334raw.Alias.Security = nil335err := gob.NewEncoder(&b).Encode(raw)336return b.Bytes(), err337}338
339raw.Security = make([]map[string]struct {340List []string341Pad bool342}, 0, len(op.Security))343for _, req := range op.Security {344v := make(map[string]struct {345List []string346Pad bool347}, len(req))348for k, val := range req {349v[k] = struct {350List []string351Pad bool352}{353List: val,354}355}356raw.Security = append(raw.Security, v)357}358
359err := gob.NewEncoder(&b).Encode(raw)360return b.Bytes(), err361}
362
363// GobDecode provides a safe gob decoder for Operation, including empty security requirements
364func (op *OperationProps) GobDecode(b []byte) error {365var raw gobAlias366
367buf := bytes.NewBuffer(b)368err := gob.NewDecoder(buf).Decode(&raw)369if err != nil {370return err371}372if raw.Alias == nil {373return nil374}375
376switch {377case raw.SecurityIsEmpty:378// empty, but non-nil security requirement379raw.Alias.Security = []map[string][]string{}380case len(raw.Alias.Security) == 0:381// nil security requirement382raw.Alias.Security = nil383default:384raw.Alias.Security = make([]map[string][]string, 0, len(raw.Security))385for _, req := range raw.Security {386v := make(map[string][]string, len(req))387for k, val := range req {388v[k] = make([]string, 0, len(val.List))389v[k] = append(v[k], val.List...)390}391raw.Alias.Security = append(raw.Alias.Security, v)392}393}394
395*op = *(*OperationProps)(raw.Alias)396return nil397}
398