Skip to content

Commit caed42a

Browse files
Add ErrorTransport (#114)
See https://github.com/hashicorp/go-cleanhttp for example on the importance of not using http.DefaultClient.
1 parent 12c3cf7 commit caed42a

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

transport.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,12 @@ func DoerTransport(cl interface {
115115
}) Transport {
116116
return RoundTripFunc(cl.Do)
117117
}
118+
119+
// ErrorTransport always returns the specified error instead of connecting.
120+
// It is intended for use in testing
121+
// or to prevent accidental use of http.DefaultClient.
122+
func ErrorTransport(err error) Transport {
123+
return RoundTripFunc(func(req *http.Request) (*http.Response, error) {
124+
return nil, err
125+
})
126+
}

transport_example_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"context"
66
"crypto/md5"
7+
"errors"
78
"fmt"
89
"io"
910
"net/http"
@@ -111,9 +112,8 @@ func ExampleLogTransport() {
111112
fmt.Println("Error!", err)
112113
}
113114
// Works for bad responses too
114-
baseTrans = requests.RoundTripFunc(func(req *http.Request) (*http.Response, error) {
115-
return nil, fmt.Errorf("can't connect")
116-
})
115+
baseTrans = requests.ErrorTransport(errors.New("can't connect"))
116+
117117
trans = requests.LogTransport(baseTrans, logger)
118118

119119
if err := requests.

0 commit comments

Comments
 (0)