Skip to content

Commit

Permalink
Use original context (#6)
Browse files Browse the repository at this point in the history
Signed-off-by: Oleg Kovalov <[email protected]>
  • Loading branch information
cristaloleg authored Jun 8, 2021
1 parent 71f083b commit 980f5db
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
3 changes: 1 addition & 2 deletions hedged.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ type hedgedTransport struct {
}

func (ht *hedgedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
mainCtx, mainCtxCancel := context.WithCancel(req.Context())
defer mainCtxCancel()
mainCtx := req.Context()

timeout := ht.timeout
if timeout == 0 {
Expand Down
18 changes: 16 additions & 2 deletions hedged_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
Expand Down Expand Up @@ -67,17 +68,27 @@ func TestNoTimeout(t *testing.T) {
func TestFirstIsOK(t *testing.T) {
url := testServerURL(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})

req, err := http.NewRequest("GET", url, http.NoBody)
if err != nil {
t.Fatal(err)
}

_, err = NewClient(10*time.Millisecond, 10, nil).Do(req)
resp, err := NewClient(10*time.Millisecond, 10, nil).Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(body) != "ok" {
t.Fatalf("want ok, got %s", string(body))
}
}

func TestBestResponse(t *testing.T) {
Expand All @@ -88,7 +99,10 @@ func TestBestResponse(t *testing.T) {
time.Sleep(timeout[rand.Int()%len(timeout)])
})

req, err := http.NewRequest("GET", url, http.NoBody)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
if err != nil {
t.Fatal(err)
}
Expand Down

0 comments on commit 980f5db

Please sign in to comment.