oauth2: add examples for basic/custom HTTP client
- provides a bare and custom context example
demonstrating that http client attributes are
not always passed along.
- adds clarifying note to the oauth2.go NewClient
godoc.
- trim down example_test
Change-Id: Iad6697eed83429c36b9ba0efc43293f4910938fb
Reviewed-on: https://go-review.googlesource.com/36553
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: JBD <jbd@google.com>
diff --git a/example_test.go b/example_test.go
index 378c70d..55c5c04 100644
--- a/example_test.go
+++ b/example_test.go
@@ -48,7 +48,7 @@
client.Get("...")
}
-func ExampleHTTPClient() {
+func ExampleCustomHTTP() {
hc := &http.Client{Timeout: 2 * time.Second}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, hc)
@@ -57,15 +57,24 @@
ClientSecret: "YOUR_CLIENT_SECRET",
Scopes: []string{"SCOPE1", "SCOPE2"},
Endpoint: oauth2.Endpoint{
- AuthURL: "https://provider.com/o/oauth2/auth",
TokenURL: "https://provider.com/o/oauth2/token",
+ AuthURL: "https://provider.com/o/oauth2/auth",
},
}
- // Exchange request will be made by the custom
- // HTTP client, hc.
- _, err := conf.Exchange(ctx, "foo")
+ tokenSource, err := conf.PasswordCredentialsToken(ctx, "YOUR_USERNAME", "YOUR_PASSWORD")
if err != nil {
log.Fatal(err)
}
+
+ // The returned client does not reuse
+ // properties from the hc HTTP Client.
+ client := oauth2.NewClient(ctx, tokenSource)
+
+ resp, err := client.Get("http://www.example.com")
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ _ = resp // use the response
}
diff --git a/oauth2.go b/oauth2.go
index 3e4835d..4bafe87 100644
--- a/oauth2.go
+++ b/oauth2.go
@@ -291,6 +291,10 @@
// NewClient creates an *http.Client from a Context and TokenSource.
// The returned client is not valid beyond the lifetime of the context.
//
+// Note that if a custom *http.Client is provided via the Context it
+// is used only for token acquisition and is not used to configure the
+// *http.Client returned from NewClient.
+//
// As a special case, if src is nil, a non-OAuth2 client is returned
// using the provided context. This exists to support related OAuth2
// packages.