Skip to content

Commit d89af98

Browse files
rakyllodeke-em
authored andcommitted
oauth2: improve the custom HTTP client example
Fix the broken build and make it consistent with the first example. Change-Id: I7c240b826397e6ec04294a2c9de89762d68643de Reviewed-on: https://go-review.googlesource.com/61050 Run-TryBot: JBD <[email protected]> Reviewed-by: Emmanuel Odeke <[email protected]>
1 parent 3d1522b commit d89af98

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

example_test.go

+19-10
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,8 @@ func ExampleConfig() {
4848
client.Get("...")
4949
}
5050

51-
func ExampleCustomHTTP() {
52-
hc := &http.Client{Timeout: 2 * time.Second}
53-
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, hc)
51+
func ExampleConfig_customHTTP() {
52+
ctx := context.Background()
5453

5554
conf := &oauth2.Config{
5655
ClientID: "YOUR_CLIENT_ID",
@@ -62,19 +61,29 @@ func ExampleCustomHTTP() {
6261
},
6362
}
6463

65-
tokenSource, err := conf.PasswordCredentialsToken(ctx, "YOUR_USERNAME", "YOUR_PASSWORD")
66-
if err != nil {
64+
// Redirect user to consent page to ask for permission
65+
// for the scopes specified above.
66+
url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
67+
fmt.Printf("Visit the URL for the auth dialog: %v", url)
68+
69+
// Use the authorization code that is pushed to the redirect
70+
// URL. Exchange will do the handshake to retrieve the
71+
// initial access token. The HTTP Client returned by
72+
// conf.Client will refresh the token as necessary.
73+
var code string
74+
if _, err := fmt.Scan(&code); err != nil {
6775
log.Fatal(err)
6876
}
6977

70-
// The returned client does not reuse
71-
// properties from the hc HTTP Client.
72-
client := oauth2.NewClient(ctx, tokenSource)
78+
// Use the custom HTTP client when requesting a token.
79+
httpClient := &http.Client{Timeout: 2 * time.Second}
80+
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
7381

74-
resp, err := client.Get("http://www.example.com")
82+
tok, err := conf.Exchange(ctx, code)
7583
if err != nil {
7684
log.Fatal(err)
7785
}
7886

79-
_ = resp // use the response
87+
client := conf.Client(ctx, tok)
88+
_ = client
8089
}

0 commit comments

Comments
 (0)