Skip to content

Commit

Permalink
Add ErrorTransport (#114)
Browse files Browse the repository at this point in the history
See https://github.com/hashicorp/go-cleanhttp for example on the importance of not using http.DefaultClient.
  • Loading branch information
earthboundkid authored Jul 21, 2024
1 parent 12c3cf7 commit caed42a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
9 changes: 9 additions & 0 deletions transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,12 @@ func DoerTransport(cl interface {
}) Transport {
return RoundTripFunc(cl.Do)
}

// ErrorTransport always returns the specified error instead of connecting.
// It is intended for use in testing
// or to prevent accidental use of http.DefaultClient.
func ErrorTransport(err error) Transport {
return RoundTripFunc(func(req *http.Request) (*http.Response, error) {
return nil, err
})
}
6 changes: 3 additions & 3 deletions transport_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/md5"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -111,9 +112,8 @@ func ExampleLogTransport() {
fmt.Println("Error!", err)
}
// Works for bad responses too
baseTrans = requests.RoundTripFunc(func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("can't connect")
})
baseTrans = requests.ErrorTransport(errors.New("can't connect"))

trans = requests.LogTransport(baseTrans, logger)

if err := requests.
Expand Down

0 comments on commit caed42a

Please sign in to comment.