@@ -8,45 +8,51 @@ import (
8
8
"github.com/int128/oauth2cli"
9
9
"golang.org/x/oauth2"
10
10
"golang.org/x/oauth2/google"
11
+ "golang.org/x/sync/errgroup"
12
+ "golang.org/x/xerrors"
11
13
)
12
14
13
15
func main () {
16
+ ctx := context .Background ()
14
17
clientID , clientSecret := os .Getenv ("GOOGLE_CLIENT_ID" ), os .Getenv ("GOOGLE_CLIENT_SECRET" )
15
18
if clientID == "" || clientSecret == "" {
16
19
log .Fatalf ("You need to set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET" )
17
20
}
18
21
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 {
25
25
select {
26
26
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
31
29
}
30
+ log .Printf ("Open %s" , url )
31
+ // you can open the browser here
32
+ return nil
32
33
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 )
34
35
}
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 ,
46
36
})
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 )
49
57
}
50
- log .Printf ("Got a token: %+v" , token )
51
- log .Printf ("Your token is valid until %s" , token .Expiry )
52
58
}
0 commit comments