Skip to content

Commit 3d1522b

Browse files
zachgershrakyll
authored andcommitted
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 <[email protected]> Reviewed-by: JBD <[email protected]>
1 parent 9a379c6 commit 3d1522b

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

example_test.go

+14-5
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func ExampleConfig() {
4848
client.Get("...")
4949
}
5050

51-
func ExampleHTTPClient() {
51+
func ExampleCustomHTTP() {
5252
hc := &http.Client{Timeout: 2 * time.Second}
5353
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, hc)
5454

@@ -57,15 +57,24 @@ func ExampleHTTPClient() {
5757
ClientSecret: "YOUR_CLIENT_SECRET",
5858
Scopes: []string{"SCOPE1", "SCOPE2"},
5959
Endpoint: oauth2.Endpoint{
60-
AuthURL: "https://provider.com/o/oauth2/auth",
6160
TokenURL: "https://provider.com/o/oauth2/token",
61+
AuthURL: "https://provider.com/o/oauth2/auth",
6262
},
6363
}
6464

65-
// Exchange request will be made by the custom
66-
// HTTP client, hc.
67-
_, err := conf.Exchange(ctx, "foo")
65+
tokenSource, err := conf.PasswordCredentialsToken(ctx, "YOUR_USERNAME", "YOUR_PASSWORD")
66+
if err != nil {
67+
log.Fatal(err)
68+
}
69+
70+
// The returned client does not reuse
71+
// properties from the hc HTTP Client.
72+
client := oauth2.NewClient(ctx, tokenSource)
73+
74+
resp, err := client.Get("http://www.example.com")
6875
if err != nil {
6976
log.Fatal(err)
7077
}
78+
79+
_ = resp // use the response
7180
}

oauth2.go

+4
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,10 @@ var HTTPClient internal.ContextKey
291291
// NewClient creates an *http.Client from a Context and TokenSource.
292292
// The returned client is not valid beyond the lifetime of the context.
293293
//
294+
// Note that if a custom *http.Client is provided via the Context it
295+
// is used only for token acquisition and is not used to configure the
296+
// *http.Client returned from NewClient.
297+
//
294298
// As a special case, if src is nil, a non-OAuth2 client is returned
295299
// using the provided context. This exists to support related OAuth2
296300
// packages.

0 commit comments

Comments
 (0)