-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathproxy.go
290 lines (237 loc) · 6.54 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package proxy
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"github.com/go-openapi/errors"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
"github.com/gorilla/mux"
)
type Proxy struct {
// Opts
target string
verbose bool
router *mux.Router
routes map[*mux.Route]*spec.Operation
reverseProxy http.Handler
reporter Reporter
doc interface{} // This is useful for validate (TODO: find a better way)
spec *spec.Swagger
pendingOperations map[*spec.Operation]struct{}
}
type ProxyOpt func(*Proxy)
func WithTarget(target string) ProxyOpt { return func(proxy *Proxy) { proxy.target = target } }
func WithVerbose(v bool) ProxyOpt { return func(proxy *Proxy) { proxy.verbose = v } }
func New(s *spec.Swagger, reporter Reporter, opts ...ProxyOpt) (*Proxy, error) {
proxy := &Proxy{
target: "http://localhost:8080",
router: mux.NewRouter(),
routes: make(map[*mux.Route]*spec.Operation),
reporter: reporter,
}
if err := proxy.SetSpec(s); err != nil {
return nil, err
}
for _, opt := range opts {
opt(proxy)
}
rpURL, err := url.Parse(proxy.target)
if err != nil {
return nil, err
}
proxy.reverseProxy = httputil.NewSingleHostReverseProxy(rpURL)
proxy.router.NotFoundHandler = http.HandlerFunc(proxy.notFound)
proxy.registerPaths()
return proxy, nil
}
func (proxy *Proxy) SetSpec(spec *spec.Swagger) error {
// validate.NewSchemaValidator requires the spec as an interface{}
// That's why we Unmarshal(Marshal()) the document
data, err := json.Marshal(spec)
if err != nil {
return err
}
var doc interface{}
if err := json.Unmarshal(data, &doc); err != nil {
return err
}
proxy.doc = doc
proxy.spec = spec
proxy.registerPaths()
return nil
}
func (proxy *Proxy) Router() http.Handler {
return proxy.router
}
func (proxy *Proxy) Target() string {
return proxy.target
}
func (proxy *Proxy) registerPaths() {
proxy.pendingOperations = make(map[*spec.Operation]struct{})
base := proxy.spec.BasePath
router := mux.NewRouter()
WalkOps(proxy.spec, func(path, method string, op *spec.Operation) {
newPath := base + path
if proxy.verbose {
fmt.Printf("Register %s %s\n", method, newPath)
}
route := router.Handle(newPath, proxy.newHandler()).Methods(method)
proxy.routes[route] = op
proxy.pendingOperations[op] = struct{}{}
})
*proxy.router = *router
}
func (proxy *Proxy) notFound(w http.ResponseWriter, req *http.Request) {
proxy.reporter.Warning(req, "Route not defined on the Spec")
proxy.reverseProxy.ServeHTTP(w, req)
}
func (proxy *Proxy) newHandler() http.Handler {
return proxy.Handler(proxy.reverseProxy)
}
func (proxy *Proxy) Handler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
wr := &WriterRecorder{ResponseWriter: w}
next.ServeHTTP(wr, req)
var match mux.RouteMatch
proxy.router.Match(req, &match)
op := proxy.routes[match.Route]
if match.Handler == nil || op == nil {
proxy.reporter.Warning(req, "Route not defined on the Spec")
// Route hasn't been registered on the muxer
return
}
proxy.operationExecuted(op)
if err := proxy.Validate(wr, op); err != nil {
proxy.reporter.Error(req, err)
} else {
proxy.reporter.Success(req)
}
}
return http.HandlerFunc(fn)
}
type validatorFunc func(Response, *spec.Operation) error
func (proxy *Proxy) Validate(resp Response, op *spec.Operation) error {
if _, ok := op.Responses.StatusCodeResponses[resp.Status()]; !ok {
return fmt.Errorf("Server Status %d not defined by the spec", resp.Status())
}
var validators = []validatorFunc{
proxy.ValidateMIME,
proxy.ValidateHeaders,
proxy.ValidateBody,
}
var errs []error
for _, v := range validators {
if err := v(resp, op); err != nil {
if cErr, ok := err.(*errors.CompositeError); ok {
errs = append(errs, cErr.Errors...)
} else {
errs = append(errs, err)
}
}
}
if len(errs) == 0 {
return nil
}
return errors.CompositeValidationError(errs...)
}
func (proxy *Proxy) ValidateMIME(resp Response, op *spec.Operation) error {
// Use Operation Spec or fallback to root
produces := op.Produces
if len(produces) == 0 {
produces = proxy.spec.Produces
}
ct := resp.Header().Get("Content-Type")
if len(produces) == 0 {
return nil
}
for _, mime := range produces {
if ct == mime {
return nil
}
}
return fmt.Errorf("Content-Type Error: Should produce %q, but got: '%s'", produces, ct)
}
func (proxy *Proxy) ValidateHeaders(resp Response, op *spec.Operation) error {
var errs []error
r := op.Responses.StatusCodeResponses[resp.Status()]
for key, spec := range r.Headers {
if err := validateHeaderValue(key, resp.Header().Get(key), &spec); err != nil {
errs = append(errs, err)
}
}
if len(errs) == 0 {
return nil
}
return errors.CompositeValidationError(errs...)
}
func (proxy *Proxy) ValidateBody(resp Response, op *spec.Operation) error {
r := op.Responses.StatusCodeResponses[resp.Status()]
if r.Schema == nil {
return nil
}
var data interface{}
if err := json.Unmarshal(resp.Body(), &data); err != nil {
return err
}
v := validate.NewSchemaValidator(r.Schema, proxy.doc, "", strfmt.Default)
if result := v.Validate(data); result.HasErrors() {
return result.AsError()
}
return nil
}
func validateHeaderValue(key, value string, spec *spec.Header) error {
if value == "" {
return fmt.Errorf("%s in headers is missing", key)
}
// TODO: Implement the rest of the format validators
switch spec.Format {
case "int32":
_, err := swag.ConvertInt32(value)
return err
case "date-time":
_, err := strfmt.ParseDateTime(value)
return err
}
return nil
}
func (proxy *Proxy) PendingOperations() []*spec.Operation {
var ops []*spec.Operation
for op, _ := range proxy.pendingOperations {
ops = append(ops, op)
}
return ops
}
func (proxy *Proxy) operationExecuted(op *spec.Operation) {
delete(proxy.pendingOperations, op)
}
type WalkOpsFunc func(path, meth string, op *spec.Operation)
func WalkOps(spec *spec.Swagger, fn WalkOpsFunc) {
for path, props := range spec.Paths.Paths {
for meth, op := range getOperations(&props) {
fn(path, meth, op)
}
}
}
func getOperations(props *spec.PathItem) map[string]*spec.Operation {
ops := map[string]*spec.Operation{
"DELETE": props.Delete,
"GET": props.Get,
"HEAD": props.Head,
"OPTIONS": props.Options,
"PATCH": props.Patch,
"POST": props.Post,
"PUT": props.Put,
}
// Keep those != nil
for key, op := range ops {
if op == nil {
delete(ops, key)
}
}
return ops
}