From 3d1522b2688977b7f4598d1f28b5e147c41640e7 Mon Sep 17 00:00:00 2001 From: zachgersh Date: Tue, 7 Feb 2017 19:56:20 -0600 Subject: [PATCH] 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 Reviewed-by: JBD --- example_test.go | 19 ++++++++++++++----- oauth2.go | 4 ++++ 2 files changed, 18 insertions(+), 5 deletions(-) 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 @@ func ExampleConfig() { 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 @@ func ExampleHTTPClient() { 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 @@ var HTTPClient internal.ContextKey // 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.