-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
75 lines (64 loc) · 1.76 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package gmailext
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/option"
ghttp "google.golang.org/api/transport/http"
)
func NewService(
ctx context.Context,
gmailCredentials string,
tokenReader io.Reader,
baseTransport http.RoundTripper,
) (*gmail.Service, error) {
config, err := getOauth2Config(ctx, gmailCredentials)
if err != nil {
return nil, fmt.Errorf("get oauth2 config: %w", err)
}
var token oauth2.Token
if err := json.NewDecoder(tokenReader).Decode(&token); err != nil {
return nil, fmt.Errorf("json decode token: %w", err)
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{
Timeout: 20 * time.Second,
Transport: baseTransport,
})
tokenSource := config.TokenSource(ctx, &token)
transport, err := ghttp.NewTransport(ctx, baseTransport, option.WithTokenSource(tokenSource))
if err != nil {
return nil, fmt.Errorf("new transport: %w", err)
}
client := &http.Client{
Timeout: 20 * time.Second,
Transport: transport,
}
service, err := gmail.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
return nil, fmt.Errorf("new service: %w", err)
}
return service, nil
}
const gmailScope = gmail.GmailReadonlyScope
func getOauth2Config(
ctx context.Context,
gmailCredentials string,
) (*oauth2.Config, error) {
params := google.CredentialsParams{}
params.Scopes = []string{gmailScope}
credentials, err := google.CredentialsFromJSONWithParams(ctx, []byte(gmailCredentials), params)
if err != nil {
return nil, err
}
config, err := google.ConfigFromJSON(credentials.JSON, gmailScope)
if err != nil {
return nil, fmt.Errorf("config from json: %w", err)
}
return config, nil
}