-
Notifications
You must be signed in to change notification settings - Fork 1
/
transport.go
71 lines (61 loc) · 1.47 KB
/
transport.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
package oaichecker
import (
"bytes"
"io"
"io/ioutil"
"net/http"
)
// Transport is a http.RoundTripper implementation destined to be injected
// inside an htttp.Client.Transport.
//
// It allows to make HTTP calls as usual but it will intercept the
// http.Request and http.Response and will validate them against the OpenAPI
// specs given during instantiation.
type Transport struct {
Transport http.RoundTripper
analyzer *Analyzer
}
// NewTransport instantiate a new Transport with the given Specs.
func NewTransport(specs *Specs) *Transport {
return &Transport{
Transport: http.DefaultTransport,
analyzer: NewAnalyzer(specs),
}
}
// RoundTrip implement http.RoundTripper.
//
// If a validation error occures an error will returned with a new Response.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
var (
err error
body []byte
)
// GetBody is an optional func to return a new copy of Body
switch req.Body.(type) {
case nil:
req.GetBody = func() (io.ReadCloser, error) {
return http.NoBody, nil
}
default:
body, err = ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
req.GetBody = func() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(body)), nil
}
}
req.Body, err = req.GetBody()
if err != nil {
return nil, err
}
res, err := t.Transport.RoundTrip(req)
if err != nil {
return nil, err
}
err = t.analyzer.Analyze(req, res)
if err != nil {
return nil, err
}
return res, err
}