-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspyserver.go
67 lines (56 loc) · 1.81 KB
/
spyserver.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
package spyserver
import (
"io"
"io/ioutil"
"net/http"
"strings"
)
// SpyServer implements the http.RoundTripper interface to serve a custom
// http.Response or error while capturing the request for later inspection
// A pointer to this type can be assigned to http.Client.Transport to
// override the default RoundTripper
type SpyServer struct {
Response *http.Response
Error error
request *http.Request
}
// RoundTrip implements the http.RoundTripper interface
func (s *SpyServer) RoundTrip(req *http.Request) (*http.Response, error) {
s.request = req
return s.Response, s.Error
}
// GetRequest returns the http.Request that was passed during the last RoundTrip
func (s *SpyServer) GetRequest() *http.Request {
return s.request
}
// CloseDetector is an io.ReadCloser that tracks whether Close has been called.
// This struct is useful because the behavior of Close after the first call is undefined.
type CloseDetector struct {
io.ReadCloser
closed bool
}
// NewCloseDetector wraps an existing io.ReadCloser.
func NewCloseDetector(rc io.ReadCloser) *CloseDetector {
var closed bool
return &CloseDetector{rc, closed}
}
// NewCloseDetectorFromString wraps a NopCloser containing the string
func NewCloseDetectorFromString(s string) *CloseDetector {
return NewCloseDetector(ioutil.NopCloser(strings.NewReader(s)))
}
// Read is a pass-through function that delegates to the wrapped Read function.
func (cd *CloseDetector) Read(p []byte) (n int, err error) {
return cd.ReadCloser.Read(p)
}
// Close delegates to the wrapped Close function and tracks whether the function was called.
func (cd *CloseDetector) Close() error {
cd.closed = true
if cd.ReadCloser == nil {
return nil
}
return cd.ReadCloser.Close()
}
// IsClosed returns whether Close was called
func (cd *CloseDetector) IsClosed() bool {
return cd.closed
}