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>
This commit is contained in:
zachgersh 2017-02-07 19:56:20 -06:00 committed by JBD
parent 9a379c6b3e
commit 3d1522b268
2 changed files with 18 additions and 5 deletions

View File

@ -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
}

View File

@ -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.