Skip to content

Commit

Permalink
Validate constructor params (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Jun 10, 2021
1 parent 78f85d7 commit 834dbad
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
16 changes: 12 additions & 4 deletions hedged.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,21 @@ func NewClient(timeout time.Duration, upto int, client *http.Client) *http.Clien
// Given RoundTripper starts a new request after a timeout from previous request.
// Starts no more than upto requests.
func NewRoundTripper(timeout time.Duration, upto int, rt http.RoundTripper) http.RoundTripper {
switch {
case timeout < 0:
panic("hedgedhttp: timeout cannot be negative")
case upto < 1:
panic("hedgedhttp: upto must be greater than 0")
}

if rt == nil {
rt = http.DefaultTransport
}

if timeout == 0 {
timeout = time.Nanosecond // smallest possible timeout if not set
}

hedged := &hedgedTransport{
rt: rt,
timeout: timeout,
Expand All @@ -50,10 +62,6 @@ func (ht *hedgedTransport) RoundTrip(req *http.Request) (*http.Response, error)
mainCtx := req.Context()

timeout := ht.timeout
if timeout == 0 {
timeout = time.Nanosecond // smallest possible timeout if not set
}

errOverall := &MultiError{}
resultCh := make(chan indexedResp, ht.upto)
errorCh := make(chan error, ht.upto)
Expand Down
22 changes: 22 additions & 0 deletions hedged_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,28 @@ import (
"time"
)

func TestValidateInput(t *testing.T) {
f := func(f func()) {
defer func() {
if r := recover(); r == nil {
t.Fatal()
}
}()

f()
}

f(func() {
NewClient(-time.Second, 0, nil)
})
f(func() {
NewClient(time.Second, -1, nil)
})
f(func() {
NewClient(time.Second, 0, nil)
})
}

func TestUpto(t *testing.T) {
var gotRequests int64

Expand Down

0 comments on commit 834dbad

Please sign in to comment.