-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
55 lines (43 loc) · 1.22 KB
/
client.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
package googledriveclient
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v2"
"google.golang.org/api/option"
)
type Client struct {
http *http.Client
service *drive.Service
}
func New() *Client {
return new(Client)
}
func (c *Client) WithAPIKey(apiKey string) (*Client, error) {
// Read credentials from an env-var:
credBytes, err := base64.StdEncoding.DecodeString(apiKey)
if err != nil {
return c, fmt.Errorf("Unable to decode Google auth key: %w", err)
}
// Authenticate and get configuration:
config, err := google.JWTConfigFromJSON(credBytes, drive.DriveScope, drive.DriveReadonlyScope, drive.DriveMetadataScope, drive.DriveMetadataReadonlyScope)
if err != nil {
return c, fmt.Errorf("Unable to get JWT config: %w", err)
}
// Prepare a spreadsheet service:
service, err := drive.NewService(context.TODO(), option.WithHTTPClient(config.Client(context.TODO())))
if err != nil {
return c, fmt.Errorf("Unable to prepare service: %w", err)
}
c.http = config.Client(context.TODO())
c.service = service
return c, nil
}
func (c *Client) HTTP() *http.Client {
return c.http
}
func (c *Client) Service() *drive.Service {
return c.service
}