Skip to content

Commit 2baa8a1

Browse files
committed
internal: primarily use the HTTP client provided in the context
Change-Id: I99eaf1480ebdfbaa5b64ac17203fbf14bf887962 Reviewed-on: https://go-review.googlesource.com/17396 Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org> Reviewed-by: Chris Broadfoot <cbro@golang.org>
1 parent 442624c commit 2baa8a1

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

internal/transport.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ func RegisterContextClientFunc(fn ContextClientFunc) {
3333
}
3434

3535
func ContextClient(ctx context.Context) (*http.Client, error) {
36+
if ctx != nil {
37+
if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
38+
return hc, nil
39+
}
40+
}
3641
for _, fn := range contextClientFuncs {
3742
c, err := fn(ctx)
3843
if err != nil {
@@ -42,9 +47,6 @@ func ContextClient(ctx context.Context) (*http.Client, error) {
4247
return c, nil
4348
}
4449
}
45-
if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
46-
return hc, nil
47-
}
4850
return http.DefaultClient, nil
4951
}
5052

internal/transport_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright 2015 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package internal
6+
7+
import (
8+
"net/http"
9+
"testing"
10+
11+
"golang.org/x/net/context"
12+
)
13+
14+
func TestContextClient(t *testing.T) {
15+
rc := &http.Client{}
16+
RegisterContextClientFunc(func(context.Context) (*http.Client, error) {
17+
return rc, nil
18+
})
19+
20+
c := &http.Client{}
21+
ctx := context.WithValue(nil, HTTPClient, c)
22+
23+
hc, err := ContextClient(ctx)
24+
if err != nil {
25+
t.Fatalf("want valid client; got err = %v", err)
26+
}
27+
if hc != c {
28+
t.Fatalf("want context client = %p; got = %p", c, hc)
29+
}
30+
31+
hc, err = ContextClient(context.TODO())
32+
if err != nil {
33+
t.Fatalf("want valid client; got err = %v", err)
34+
}
35+
if hc != rc {
36+
t.Fatalf("want registered client = %p; got = %p", c, hc)
37+
}
38+
}

0 commit comments

Comments
 (0)