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>
This commit is contained in:
Burcu Dogan 2015-12-03 13:21:41 -08:00
parent 442624c9ec
commit 2baa8a1b93
2 changed files with 43 additions and 3 deletions

View File

@ -33,6 +33,11 @@ func RegisterContextClientFunc(fn ContextClientFunc) {
} }
func ContextClient(ctx context.Context) (*http.Client, error) { func ContextClient(ctx context.Context) (*http.Client, error) {
if ctx != nil {
if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
return hc, nil
}
}
for _, fn := range contextClientFuncs { for _, fn := range contextClientFuncs {
c, err := fn(ctx) c, err := fn(ctx)
if err != nil { if err != nil {
@ -42,9 +47,6 @@ func ContextClient(ctx context.Context) (*http.Client, error) {
return c, nil return c, nil
} }
} }
if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
return hc, nil
}
return http.DefaultClient, nil return http.DefaultClient, nil
} }

View File

@ -0,0 +1,38 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package internal
import (
"net/http"
"testing"
"golang.org/x/net/context"
)
func TestContextClient(t *testing.T) {
rc := &http.Client{}
RegisterContextClientFunc(func(context.Context) (*http.Client, error) {
return rc, nil
})
c := &http.Client{}
ctx := context.WithValue(nil, HTTPClient, c)
hc, err := ContextClient(ctx)
if err != nil {
t.Fatalf("want valid client; got err = %v", err)
}
if hc != c {
t.Fatalf("want context client = %p; got = %p", c, hc)
}
hc, err = ContextClient(context.TODO())
if err != nil {
t.Fatalf("want valid client; got err = %v", err)
}
if hc != rc {
t.Fatalf("want registered client = %p; got = %p", c, hc)
}
}