...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package spec
16
17 import (
18 "encoding/json"
19 "fmt"
20 "reflect"
21 "strconv"
22 "strings"
23
24 "github.com/go-openapi/swag"
25 )
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 type Responses struct {
41 VendorExtensible
42 ResponsesProps
43 }
44
45
46 func (r Responses) JSONLookup(token string) (interface{}, error) {
47 if token == "default" {
48 return r.Default, nil
49 }
50 if ex, ok := r.Extensions[token]; ok {
51 return &ex, nil
52 }
53 if i, err := strconv.Atoi(token); err == nil {
54 if scr, ok := r.StatusCodeResponses[i]; ok {
55 return scr, nil
56 }
57 }
58 return nil, fmt.Errorf("object has no field %q", token)
59 }
60
61
62 func (r *Responses) UnmarshalJSON(data []byte) error {
63 if err := json.Unmarshal(data, &r.ResponsesProps); err != nil {
64 return err
65 }
66
67 if err := json.Unmarshal(data, &r.VendorExtensible); err != nil {
68 return err
69 }
70 if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) {
71 r.ResponsesProps = ResponsesProps{}
72 }
73 return nil
74 }
75
76
77 func (r Responses) MarshalJSON() ([]byte, error) {
78 b1, err := json.Marshal(r.ResponsesProps)
79 if err != nil {
80 return nil, err
81 }
82 b2, err := json.Marshal(r.VendorExtensible)
83 if err != nil {
84 return nil, err
85 }
86 concated := swag.ConcatJSON(b1, b2)
87 return concated, nil
88 }
89
90
91
92
93 type ResponsesProps struct {
94 Default *Response
95 StatusCodeResponses map[int]Response
96 }
97
98
99 func (r ResponsesProps) MarshalJSON() ([]byte, error) {
100 toser := map[string]Response{}
101 if r.Default != nil {
102 toser["default"] = *r.Default
103 }
104 for k, v := range r.StatusCodeResponses {
105 toser[strconv.Itoa(k)] = v
106 }
107 return json.Marshal(toser)
108 }
109
110
111 func (r *ResponsesProps) UnmarshalJSON(data []byte) error {
112 var res map[string]json.RawMessage
113 if err := json.Unmarshal(data, &res); err != nil {
114 return err
115 }
116
117 if v, ok := res["default"]; ok {
118 var defaultRes Response
119 if err := json.Unmarshal(v, &defaultRes); err != nil {
120 return err
121 }
122 r.Default = &defaultRes
123 delete(res, "default")
124 }
125 for k, v := range res {
126 if !strings.HasPrefix(k, "x-") {
127 var statusCodeResp Response
128 if err := json.Unmarshal(v, &statusCodeResp); err != nil {
129 return err
130 }
131 if nk, err := strconv.Atoi(k); err == nil {
132 if r.StatusCodeResponses == nil {
133 r.StatusCodeResponses = map[int]Response{}
134 }
135 r.StatusCodeResponses[nk] = statusCodeResp
136 }
137 }
138 }
139 return nil
140 }
141
View as plain text