1
1
package oaichecker
2
2
3
3
import (
4
+ "bytes"
4
5
"encoding/json"
5
6
"errors"
6
7
"fmt"
8
+ "io/ioutil"
7
9
"net/http"
8
10
"strconv"
9
11
"strings"
@@ -60,7 +62,7 @@ func createRouter(analyzer *analysis.Spec) *denco.Router {
60
62
return r
61
63
}
62
64
63
- func (t * Analyzer ) Analyze (req * http.Request ) error {
65
+ func (t * Analyzer ) Analyze (req * http.Request , res * http. Response ) error {
64
66
if req == nil {
65
67
return errors .New ("no request defined" )
66
68
}
@@ -95,7 +97,45 @@ func (t *Analyzer) Analyze(req *http.Request) error {
95
97
}
96
98
}
97
99
98
- return nil
100
+ err := t .validateResponse (res , operation .Responses )
101
+
102
+ return err
103
+ }
104
+
105
+ func (t * Analyzer ) validateResponse (res * http.Response , resSpec * spec.Responses ) error {
106
+ for status , response := range resSpec .StatusCodeResponses {
107
+ if status == res .StatusCode {
108
+
109
+ body , err := ioutil .ReadAll (res .Body )
110
+ if err != nil {
111
+ return err
112
+ }
113
+
114
+ res .Body = ioutil .NopCloser (bytes .NewReader (body ))
115
+
116
+ if response .ResponseProps .Schema == nil {
117
+ if len (body ) > 0 {
118
+ return fmt .Errorf ("validation failure list:\n no response body defined inside the specs but have %q" , body )
119
+ }
120
+ return nil
121
+ }
122
+
123
+ var input interface {}
124
+ err = json .Unmarshal (body , & input )
125
+ if err != nil {
126
+ return fmt .Errorf ("failed to parse json body: %s" , err )
127
+ }
128
+
129
+ err = validate .AgainstSchema (response .Schema , input , strfmt .Default )
130
+ if err != nil {
131
+ return err
132
+ }
133
+
134
+ return nil
135
+ }
136
+ }
137
+
138
+ return fmt .Errorf ("validation failure list:\n response status %s not defined inside the specs" , res .Status )
99
139
}
100
140
101
141
func (t * Analyzer ) validateBodyParameter (req * http.Request , param * spec.Parameter ) error {
@@ -110,17 +150,7 @@ func (t *Analyzer) validateBodyParameter(req *http.Request, param *spec.Paramete
110
150
return err
111
151
}
112
152
113
- paramRef := param .ParamProps .Schema .Ref .String ()
114
-
115
- var schema * spec.Schema
116
- for _ , def := range t .analyzer .AllDefinitions () {
117
- if paramRef == def .Ref .String () {
118
- schema = def .Schema
119
- break
120
- }
121
- }
122
-
123
- err = validate .AgainstSchema (schema , input , strfmt .Default )
153
+ err = validate .AgainstSchema (param .Schema , input , strfmt .Default )
124
154
if err != nil {
125
155
return err
126
156
}
0 commit comments