-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
47 lines (40 loc) · 1.1 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
package tenuki
import (
"net/http"
"net/http/httptest"
"testing"
)
type RoundTripFunc func(*http.Request) (*http.Response, error)
func (f RoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}
func HandlerTripperFunc(handle func(w http.ResponseWriter, r *http.Request)) *HandlerTripper {
return &HandlerTripper{
Handler: http.HandlerFunc(handle),
}
}
type HandlerTripper struct {
Before func(*http.Request)
Handler http.Handler
After func(*http.Response, *http.Request)
}
func (t *HandlerTripper) RoundTrip(r *http.Request) (*http.Response, error) {
if t.Before != nil {
t.Before(r)
}
w := httptest.NewRecorder()
t.Handler.ServeHTTP(w, r)
res := w.Result()
if t.After != nil {
t.After(res, r)
}
return res, nil
}
// NewErrorTransport returns a transport that returns error. this is one of the test utilities.
func NewErrorTransport(t *testing.T, genErr func() error) RoundTripFunc {
return func(*http.Request) (*http.Response, error) {
err := genErr()
t.Logf("test helper -- returns error %T in transport (for %s) ..", err, t.Name())
return nil, err
}
}