Skip to content

Commit 74a6a5f

Browse files
committed
Fix example to wait for all goroutines
1 parent 54c4238 commit 74a6a5f

File tree

1 file changed

+32
-26
lines changed

1 file changed

+32
-26
lines changed

example/main.go

+32-26
Original file line numberDiff line numberDiff line change
@@ -8,45 +8,51 @@ import (
88
"github.com/int128/oauth2cli"
99
"golang.org/x/oauth2"
1010
"golang.org/x/oauth2/google"
11+
"golang.org/x/sync/errgroup"
12+
"golang.org/x/xerrors"
1113
)
1214

1315
func main() {
16+
ctx := context.Background()
1417
clientID, clientSecret := os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET")
1518
if clientID == "" || clientSecret == "" {
1619
log.Fatalf("You need to set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET")
1720
}
1821

19-
ctx := context.Background()
20-
21-
// open the browser on ready (this is optional)
22-
ready := make(chan string)
23-
defer close(ready)
24-
go func() {
22+
ready := make(chan string, 1)
23+
var eg errgroup.Group
24+
eg.Go(func() error {
2525
select {
2626
case url, ok := <-ready:
27-
if ok {
28-
log.Printf("Open %s", url)
29-
} else {
30-
log.Printf("channel has been closed while waiting for authorization")
27+
if !ok {
28+
return nil
3129
}
30+
log.Printf("Open %s", url)
31+
// you can open the browser here
32+
return nil
3233
case err := <-ctx.Done():
33-
log.Printf("context done while waiting for authorization: %s", err)
34+
return xerrors.Errorf("context done while waiting for authorization: %w", err)
3435
}
35-
}()
36-
37-
// perform authorization
38-
token, err := oauth2cli.GetToken(ctx, oauth2cli.Config{
39-
OAuth2Config: oauth2.Config{
40-
ClientID: clientID,
41-
ClientSecret: clientSecret,
42-
Endpoint: google.Endpoint,
43-
Scopes: []string{"email"},
44-
},
45-
LocalServerReadyChan: ready,
4636
})
47-
if err != nil {
48-
log.Fatalf("Could not get a token: %s", err)
37+
eg.Go(func() error {
38+
defer close(ready)
39+
token, err := oauth2cli.GetToken(ctx, oauth2cli.Config{
40+
OAuth2Config: oauth2.Config{
41+
ClientID: clientID,
42+
ClientSecret: clientSecret,
43+
Endpoint: google.Endpoint,
44+
Scopes: []string{"email"},
45+
},
46+
LocalServerReadyChan: ready,
47+
})
48+
if err != nil {
49+
return xerrors.Errorf("could not get a token: %w", err)
50+
}
51+
log.Printf("Got a token: %+v", token)
52+
log.Printf("Your token is valid until %s", token.Expiry)
53+
return nil
54+
})
55+
if err := eg.Wait(); err != nil {
56+
log.Printf("error while authorization: %s", err)
4957
}
50-
log.Printf("Got a token: %+v", token)
51-
log.Printf("Your token is valid until %s", token.Expiry)
5258
}

0 commit comments

Comments
 (0)