Expert guidance for using the Google Drive API with Go, including OAuth2 authentication, file operations (list, upload, download, search), folder management, permissions, and best practices. Use when building Go applications that interact with Google Drive, implementing file storage/sync features, managing Drive permissions, or any Google Drive integration tasks in Go.
This skill provides guidance for working with Google Drive API v3 in Go applications.
Google Drive API uses OAuth2 for authentication. Set up credentials:
import (
"context"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
// Read credentials from JSON file (from Google Cloud Console)
b, err := os.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
// Configure OAuth2 with required scopes
config, err := google.ConfigFromJSON(b, drive.DriveScope)
if err != nil {
log.Fatalf("Unable to parse client secret file: %v", err)
}
// Get authenticated client
client := getClient(config)
// Create Drive service
srv, err := drive.NewService(ctx, option.WithHTTPClient(client))
drive.DriveScope - Full access to Drivedrive.DriveFileScope - Access to files created by the appdrive.DriveMetadataReadonlyScope - Read-only metadata accessdrive.DriveReadonlyScope - Read-only accessSee references/auth.md for complete OAuth2 implementation including token storage and retrieval.
r, err := srv.Files.List().
PageSize(10).
Fields("nextPageToken, files(id, name, mimeType, size)").
Do()
if err != nil {
log.Fatalf("Unable to retrieve files: %v", err)
}
for _, file := range r.Files {
fmt.Printf("%s (%s)\n", file.Name, file.Id)
}
file := &drive.File{
Name: "myfile.txt",
MimeType: "text/plain",
}
content, err := os.Open("local-file.txt")
if err != nil {
log.Fatalf("Unable to read file: %v", err)
}
defer content.Close()
createdFile, err := srv.Files.Create(file).Media(content).Do()
if err != nil {
log.Fatalf("Unable to create file: %v", err)
}
fmt.Printf("File ID: %s\n", createdFile.Id)
// Get file metadata
file, err := srv.Files.Get(fileId).Do()
// Download content
resp, err := srv.Files.Get(fileId).Download()
if err != nil {
log.Fatalf("Unable to download file: %v", err)
}
defer resp.Body.Close()
// Save to local file
out, err := os.Create(file.Name)
if err != nil {
log.Fatalf("Unable to create local file: %v", err)
}
defer out.Close()
io.Copy(out, resp.Body)
query := "name contains 'report' and mimeType='application/pdf'"
r, err := srv.Files.List().
Q(query).
Fields("files(id, name, createdTime)").
Do()
Common query patterns:
name = 'filename.txt' - Exact name matchname contains 'keyword' - Partial matchmimeType = 'application/pdf' - Filter by type'parent-folder-id' in parents - Files in foldertrashed = false - Exclude trashed filesfolder := &drive.File{
Name: "My Folder",
MimeType: "application/vnd.google-apps.folder",
}
createdFolder, err := srv.Files.Create(folder).Do()
if err != nil {
log.Fatalf("Unable to create folder: %v", err)
}
permission := &drive.Permission{
Type: "user",
Role: "writer",
EmailAddress: "[email protected]",
}
_, err := srv.Permissions.Create(fileId, permission).Do()
if err != nil {
log.Fatalf("Unable to share file: %v", err)
}
Permission roles: owner, organizer, fileOrganizer, writer, commenter, reader
Handle large result sets with pagination:
pageToken := ""
for {
r, err := srv.Files.List().
PageSize(100).
PageToken(pageToken).
Fields("nextPageToken, files(id, name)").
Do()
if err != nil {
log.Fatalf("Error: %v", err)
}
for _, file := range r.Files {
// Process file
}
pageToken = r.NextPageToken
if pageToken == "" {
break
}
}
Use the Fields parameter to specify which fields to return:
Fields("files(id, name, mimeType, size, createdTime, modifiedTime, webViewLink)")
Common fields: id, name, mimeType, size, createdTime, modifiedTime, parents, webViewLink, iconLink, thumbnailLink
Export Google Workspace files to different formats:
// Export Google Doc as PDF
resp, err := srv.Files.Export(fileId, "application/pdf").Download()
// Export Google Sheet as Excel
resp, err := srv.Files.Export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").Download()
text/plainapplication/pdfimage/jpegimage/pngapplication/vnd.google-apps.documentapplication/vnd.google-apps.spreadsheetapplication/vnd.google-apps.presentationapplication/vnd.google-apps.folderreferences/auth.md for complete OAuth2 implementationgo get google.golang.org/api/drive/v3
go get golang.org/x/oauth2/google