gdrive

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2026 License: MIT Imports: 12 Imported by: 0

README

gdrive

A comprehensive Go client library for Google Drive API v3 with support for file operations, folder management, streaming, partial downloads, and Google Workspace document exports.

Features

  • 📁 File Operations: List, upload, download, and stream files
  • 🗂️ Folder Management: Create folders, list files in folders with full path resolution
  • 🔄 Streaming Support: Efficient streaming for large files
  • 📊 Partial Downloads: Resume downloads and stream file chunks
  • 📄 Workspace Documents: Export Google Docs, Sheets, Slides to various formats
  • 🔐 Multiple Auth Methods: OAuth2 and Service Account support
  • 🗑️ Trash Operations: Move files to trash and restore them
  • 🔒 Thread-Safe: Safe for concurrent use

Installation

go get github.com/abiiranathan/gdrive

Prerequisites

You need Google Drive API credentials. Choose one:

  1. OAuth2 Credentials (for user authentication)

    • Go to Google Cloud Console
    • Create a project and enable Google Drive API
    • Create OAuth2 credentials
    • Download the credentials JSON file
  2. Service Account (for server-to-server)

    • Create a service account in Google Cloud Console
    • Download the service account JSON key
    • Share Drive files/folders with the service account email

Quick Start

OAuth2 Authentication
package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/abiiranathan/gdrive"
    "golang.org/x/oauth2"
)

func main() {
    ctx := context.Background()
    
    // Read OAuth2 credentials
    credentials, err := os.ReadFile("credentials.json")
    if err != nil {
        log.Fatal(err)
    }
    
    // Get OAuth2 config
    config, err := gdrive.GetConfigFromJSON(credentials)
    if err != nil {
        log.Fatal(err)
    }
    
    // Get token (implement OAuth2 flow)
    token := &oauth2.Token{
        AccessToken: "your-access-token",
        // ... other token fields
    }
    
    // Create client
    client, err := gdrive.NewDriveClientWithToken(ctx, config, token)
    if err != nil {
        log.Fatal(err)
    }
    
    // List files
    files, err := client.ListFiles(ctx)
    if err != nil {
        log.Fatal(err)
    }
    
    for _, file := range files {
        fmt.Printf("%s (%s) - %s\n", file.Name, file.ID, file.FolderPath)
    }
}
Service Account Authentication
package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/abiiranathan/gdrive"
)

func main() {
    ctx := context.Background()
    
    // Read service account credentials
    credentials, err := os.ReadFile("service-account.json")
    if err != nil {
        log.Fatal(err)
    }
    
    // Create client
    client, err := gdrive.NewDriveClientForServiceAccount(ctx, credentials)
    if err != nil {
        log.Fatal(err)
    }
    
    // Use client...
}

Usage Examples

Listing Files
// List all files
files, err := client.ListFiles(ctx)
if err != nil {
    log.Fatal(err)
}

for _, file := range files {
    fmt.Printf("Name: %s\n", file.Name)
    fmt.Printf("ID: %s\n", file.ID)
    fmt.Printf("Size: %d bytes\n", file.Size)
    fmt.Printf("MIME Type: %s\n", file.MimeType)
    fmt.Printf("Path: %s\n", file.FolderPath)
    fmt.Printf("Web Link: %s\n\n", file.WebViewLink)
}

// List files in specific folder
files, err := client.ListFilesInFolder(ctx, "folder-id")
Uploading Files
// Upload from file path
fileID, err := client.UploadFile(ctx, "/path/to/file.pdf", "file.pdf", "")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Uploaded file ID: %s\n", fileID)

// Upload to specific folder
fileID, err := client.UploadFile(ctx, "/path/to/file.pdf", "file.pdf", "folder-id")

// Upload from io.Reader (useful for web uploads)
file, _ := os.Open("document.pdf")
defer file.Close()

fileID, err := client.UploadFileFromReader(ctx, file, "document.pdf", "application/pdf", "")
Downloading Files
// Download to file
bytesWritten, err := client.DownloadFile(ctx, "file-id", "/path/to/output.pdf")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Downloaded %d bytes\n", bytesWritten)

// Stream to io.Writer (e.g., HTTP response)
var buf bytes.Buffer
bytesWritten, err := client.StreamFile(ctx, "file-id", &buf)
Partial Downloads
// Download specific byte range (useful for resumable downloads)
var buf bytes.Buffer
bytesWritten, err := client.PartialStreamFile(ctx, "file-id", &buf, 0, 1023)
if err != nil {
    log.Fatal(err)
}
// Downloads first 1024 bytes

// Or use PartialDownloadOptions
opts := gdrive.PartialDownloadOptions{
    StartByte: 1024,
    EndByte:   2047,
}
bytesWritten, err := client.PartialDownloadFile(ctx, "file-id", &buf, opts)
Exporting Google Workspace Documents
// Check if file is a Workspace document
isWorkspace, err := client.IsWorkspaceDocument(ctx, "file-id")
if err != nil {
    log.Fatal(err)
}

if isWorkspace {
    // Export to PDF
    var buf bytes.Buffer
    bytesWritten, err := client.ExportWorkspaceDocument(ctx, "file-id", &buf, gdrive.ExportFormatPDF)
    if err != nil {
        log.Fatal(err)
    }
    
    // Export to file
    bytesWritten, err := client.ExportWorkspaceDocumentToFile(
        ctx, 
        "file-id", 
        "/path/to/output.pdf", 
        gdrive.ExportFormatPDF,
    )
    
    // Get available export formats
    exportLinks, err := client.GetExportLinks(ctx, "file-id")
    for mimeType, link := range exportLinks {
        fmt.Printf("%s: %s\n", mimeType, link)
    }
}
Available Export Formats
// PDF
gdrive.ExportFormatPDF

// Microsoft Office
gdrive.ExportFormatDOCX  // Word
gdrive.ExportFormatXLSX  // Excel
gdrive.ExportFormatPPTX  // PowerPoint

// OpenDocument
gdrive.ExportFormatODT  // Text
gdrive.ExportFormatODS  // Spreadsheet
gdrive.ExportFormatODP  // Presentation

// Other formats
gdrive.ExportFormatRTF
gdrive.ExportFormatTXT
gdrive.ExportFormatHTML
gdrive.ExportFormatCSV
gdrive.ExportFormatEPUB
gdrive.ExportFormatJPEG
gdrive.ExportFormatPNG
gdrive.ExportFormatSVG
gdrive.ExportFormatZIP
Folder Operations
// Create folder
folderID, err := client.CreateFolder(ctx, "My Folder", "")
if err != nil {
    log.Fatal(err)
}

// Create subfolder
subfolderID, err := client.CreateFolder(ctx, "Subfolder", folderID)
Trash Operations
// Move file to trash (recoverable)
err := client.TrashFile(ctx, "file-id")
if err != nil {
    log.Fatal(err)
}

// Restore from trash
err := client.RestoreFile(ctx, "file-id")
if err != nil {
    log.Fatal(err)
}

// Permanently delete (irreversible!)
err := client.DeleteFile(ctx, "file-id")
if err != nil {
    log.Fatal(err)
}
Working with File Revisions
// Download specific revision (must be marked "Keep Forever")
var buf bytes.Buffer
bytesWritten, err := client.DownloadRevision(ctx, "file-id", "revision-id", &buf)

// Partial download of revision
opts := gdrive.PartialDownloadOptions{
    StartByte: 0,
    EndByte:   1023,
}
bytesWritten, err := client.PartialDownloadRevision(ctx, "file-id", "revision-id", &buf, opts)

API Reference

Types
DriveClient

Main client for interacting with Google Drive API. Thread-safe for concurrent use.

FileInfo
type FileInfo struct {
    ID          string   // Unique file identifier
    Name        string   // File name
    MimeType    string   // MIME type
    Size        int64    // Size in bytes
    WebViewLink string   // Browser view URL
    Parents     []string // Parent folder IDs
    FolderPath  string   // Full path (e.g., "My Drive/Projects/2024")
}
PartialDownloadOptions
type PartialDownloadOptions struct {
    StartByte int64 // Starting byte position (inclusive)
    EndByte   int64 // Ending byte position (inclusive)
}
Client Creation
  • NewDriveClientForServiceAccount(ctx, credentials) - Create client with service account
  • NewDriveClientWithToken(ctx, config, token) - Create client with OAuth2 token
  • GetConfigFromJSON(credentials) - Parse OAuth2 config from JSON
File Operations
  • ListFiles(ctx) - List all files with folder paths
  • ListFilesInFolder(ctx, folderID) - List files in specific folder
  • UploadFile(ctx, filePath, fileName, parentFolderID) - Upload file
  • UploadFileFromReader(ctx, reader, fileName, mimeType, parentFolderID) - Upload from reader
  • DownloadFile(ctx, fileID, outputPath) - Download to file
  • StreamFile(ctx, fileID, writer) - Stream to io.Writer
  • PartialStreamFile(ctx, fileID, writer, startByte, endByte) - Partial download
  • PartialDownloadFile(ctx, fileID, writer, opts) - Partial download with options
Folder Operations
  • CreateFolder(ctx, folderName, parentFolderID) - Create folder
Trash Operations
  • TrashFile(ctx, fileID) - Move to trash
  • RestoreFile(ctx, fileID) - Restore from trash
  • DeleteFile(ctx, fileID) - Permanently delete
Google Workspace Operations
  • IsWorkspaceDocument(ctx, fileID) - Check if file is Workspace document
  • ExportWorkspaceDocument(ctx, fileID, writer, format) - Export to format
  • ExportWorkspaceDocumentToFile(ctx, fileID, outputPath, format) - Export to file
  • GetExportLinks(ctx, fileID) - Get available export formats
Revision Operations
  • DownloadRevision(ctx, fileID, revisionID, writer) - Download revision
  • PartialDownloadRevision(ctx, fileID, revisionID, writer, opts) - Partial revision download

Error Handling

All methods return errors that should be checked. Errors are wrapped with context using fmt.Errorf with %w for error unwrapping.

files, err := client.ListFiles(ctx)
if err != nil {
    // Handle error
    log.Printf("Failed to list files: %v", err)
    return
}

Limitations

  • Maximum page size: 100 files per request
  • Partial downloads not supported for Google Workspace documents
  • Exported Workspace documents limited to 10 MB
  • Revision downloads require revision to be marked "Keep Forever"
  • Folder path resolution limited to 10 levels (prevents infinite loops)

Dependencies

golang.org/x/oauth2
google.golang.org/api/drive/v3
google.golang.org/api/option

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Author

Abiira Nathan (@abiiranathan)

Documentation

Overview

Package gdrive provides a comprehensive client library for Google Drive API v3.

This package offers a high-level interface for common Google Drive operations including:

  • File uploads and downloads with streaming support
  • Folder creation and file listing with full path resolution
  • Partial downloads for resumable transfers
  • Google Workspace document exports to various formats
  • Trash operations (move to trash, restore, permanent delete)
  • File revision management

Authentication

The package supports two authentication methods:

1. OAuth2 for user authentication:

credentials, _ := os.ReadFile("credentials.json")
config, _ := gdrive.GetConfigFromJSON(credentials)
token := &oauth2.Token{AccessToken: "..."}
client, _ := gdrive.NewDriveClientWithToken(ctx, config, token)

2. Service Account for server-to-server:

credentials, _ := os.ReadFile("service-account.json")
client, _ := gdrive.NewDriveClientForServiceAccount(ctx, credentials)

Basic Usage

// List files
files, err := client.ListFiles(ctx)
for _, file := range files {
    fmt.Printf("%s - %s\n", file.Name, file.FolderPath)
}

// Upload file
fileID, err := client.UploadFile(ctx, "/path/to/file.pdf", "file.pdf", "")

// Download file
bytesWritten, err := client.DownloadFile(ctx, fileID, "/path/to/output.pdf")

// Export Google Doc to PDF
err = client.ExportWorkspaceDocumentToFile(ctx, docID, "output.pdf", gdrive.ExportFormatPDF)

Thread Safety

DriveClient is safe for concurrent use by multiple goroutines.

Index

Constants

View Source
const MaxPageSize = 100

MaxPageSize is the maximum number of files to retrieve per API request. Google Drive API allows up to 1000, but 100 provides a good balance between API calls and memory usage.

Variables

This section is empty.

Functions

func GetConfigFromJSON

func GetConfigFromJSON(jsonCredentials []byte) (*oauth2.Config, error)

GetConfigFromJSON parses OAuth2 user credentials JSON into an oauth2.Config. This config is used to generate the authorization URL and exchange authorization codes for access tokens during the OAuth2 flow.

To obtain credentials:

  1. Go to Google Cloud Console
  2. Create OAuth2 credentials (Desktop app or Web application)
  3. Download the JSON file

Parameters:

  • jsonCredentials: Contents of the OAuth2 credentials JSON file

Returns:

  • *oauth2.Config: Configuration for OAuth2 flow
  • error: Any error encountered during parsing

Example:

credentials, _ := os.ReadFile("credentials.json")
config, err := gdrive.GetConfigFromJSON(credentials)
// Use config.AuthCodeURL() to start OAuth2 flow

Types

type DriveClient

type DriveClient struct {
	// contains filtered or unexported fields
}

DriveClient wraps the Google Drive API client. It provides high-level methods for common Drive operations. Safe for concurrent use by multiple goroutines.

func NewDriveClient added in v0.2.1

func NewDriveClient(ctx context.Context, client *http.Client) (*DriveClient, error)

NewDriveClient is the internal helper to initialize the Google Drive service. It creates a new drive.Service using the provided HTTP client.

Parameters:

  • ctx: Context for the API initialization
  • client: Authenticated HTTP client with Drive API scope

Returns:

  • *DriveClient: Initialized client ready for use
  • error: Any error encountered during service creation

func NewDriveClientForServiceAccount

func NewDriveClientForServiceAccount(ctx context.Context, jsonCredentials []byte) (*DriveClient, error)

NewDriveClientForServiceAccount creates a DriveClient using Service Account credentials. This method is ideal for server-to-server interaction where no user interaction is needed. The service account must have access to the files/folders you want to access.

To use this method:

  1. Create a service account in Google Cloud Console
  2. Download the JSON key file
  3. Share Drive files/folders with the service account email

Parameters:

  • ctx: Context for the API initialization
  • jsonCredentials: Contents of the service account JSON key file

Returns:

  • *DriveClient: Initialized client with read-only access
  • error: Any error encountered during authentication or service creation

Example:

credentials, _ := os.ReadFile("service-account.json")
client, err := gdrive.NewDriveClientForServiceAccount(ctx, credentials)
if err != nil {
    log.Fatal(err)
}

func NewDriveClientWithToken

func NewDriveClientWithToken(ctx context.Context, config *oauth2.Config, tok *oauth2.Token) (*DriveClient, error)

NewDriveClientWithToken creates a DriveClient using an existing OAuth2 token. This is the typical way a web application initializes the client after completing the OAuth2 authorization flow.

Parameters:

  • ctx: Context for the API initialization
  • config: OAuth2 configuration (obtained from GetConfigFromJSON)
  • tok: Valid OAuth2 token (obtained from OAuth2 flow)

Returns:

  • *DriveClient: Initialized client with user's Drive access
  • error: Any error encountered during client creation

Example:

config, _ := gdrive.GetConfigFromJSON(credentials)
token := &oauth2.Token{AccessToken: "...", RefreshToken: "..."}
client, err := gdrive.NewDriveClientWithToken(ctx, config, token)

func (*DriveClient) CreateFolder

func (dc *DriveClient) CreateFolder(ctx context.Context, folderName, parentFolderID string) (string, error)

CreateFolder creates a new folder in Google Drive.

Parameters:

  • ctx: Context for cancellation and timeout
  • folderName: Name of the folder to create (required)
  • parentFolderID: ID of the parent folder. Empty string creates in "My Drive" root

Returns:

  • string: Folder ID of the created folder
  • error: Any error encountered during creation

Example:

// Create folder in root
folderID, err := client.CreateFolder(ctx, "Project Files", "")

// Create subfolder
subfolderID, err := client.CreateFolder(ctx, "2024", folderID)

func (*DriveClient) DeleteFile

func (dc *DriveClient) DeleteFile(ctx context.Context, fileID string) error

DeleteFile permanently deletes a file or folder from Google Drive. WARNING: This action is irreversible. The file cannot be recovered. Consider using TrashFile instead for recoverable deletion.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file or folder to permanently delete

Returns:

  • error: Any error encountered during the operation

Example:

err := client.DeleteFile(ctx, "1aBc2DeF")
if err != nil {
    log.Printf("Failed to delete file: %v", err)
}

func (*DriveClient) DownloadFile

func (dc *DriveClient) DownloadFile(ctx context.Context, fileID, outputPath string) (int64, error)

DownloadFile downloads a file from Google Drive to a local file path. The parent directory is created automatically if it doesn't exist. This is a convenience wrapper around StreamFile for file-based downloads.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: Unique Google Drive file identifier
  • outputPath: Local file system path where file will be saved

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during download or file creation

Example:

bytesWritten, err := client.DownloadFile(ctx, "1aBc2DeF", "/downloads/document.pdf")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Downloaded %d bytes\n", bytesWritten)

func (*DriveClient) DownloadRevision

func (dc *DriveClient) DownloadRevision(ctx context.Context, fileID, revisionID string, w io.Writer) (int64, error)

DownloadRevision downloads a specific revision of a file. The revision must be marked as "Keep Forever" in Google Drive to be downloadable. This is useful for version control and accessing historical versions of files.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file
  • revisionID: ID of the specific revision to download
  • w: Destination writer for the revision content

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during download

Example:

var buf bytes.Buffer
bytesWritten, err := client.DownloadRevision(ctx, fileID, revisionID, &buf)

func (*DriveClient) ExportWorkspaceDocument

func (dc *DriveClient) ExportWorkspaceDocument(ctx context.Context, fileID string, w io.Writer, format ExportFormat) (int64, error)

ExportWorkspaceDocument exports a Google Workspace document to the specified format. Supported formats depend on the document type:

  • Google Docs: PDF, DOCX, ODT, RTF, TXT, HTML, EPUB, ZIP
  • Google Sheets: PDF, XLSX, ODS, CSV, HTML, ZIP
  • Google Slides: PDF, PPTX, ODP, TXT, JPEG, PNG, SVG
  • Google Drawings: PDF, JPEG, PNG, SVG

Note: Exported content is limited to 10 MB by Google Drive API.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the Google Workspace document
  • w: Destination writer for the exported content
  • format: Desired export format (use ExportFormat constants)

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during export

Example:

// Export Google Doc to PDF
var buf bytes.Buffer
bytesWritten, err := client.ExportWorkspaceDocument(ctx, docID, &buf, gdrive.ExportFormatPDF)

// Export Google Sheet to Excel
bytesWritten, err := client.ExportWorkspaceDocument(ctx, sheetID, &buf, gdrive.ExportFormatXLSX)

func (*DriveClient) ExportWorkspaceDocumentToFile

func (dc *DriveClient) ExportWorkspaceDocumentToFile(ctx context.Context, fileID, outputPath string, format ExportFormat) (int64, error)

ExportWorkspaceDocumentToFile exports a Google Workspace document to a local file. This is a convenience method that wraps ExportWorkspaceDocument. The parent directory is created automatically if it doesn't exist.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the Google Workspace document
  • outputPath: Local file system path where exported file will be saved
  • format: Desired export format (use ExportFormat constants)

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during export or file creation

Example:

// Export Google Doc to PDF file
bytesWritten, err := client.ExportWorkspaceDocumentToFile(ctx, docID,
    "/exports/document.pdf", gdrive.ExportFormatPDF)
func (dc *DriveClient) GetExportLinks(ctx context.Context, fileID string) (map[string]string, error)

GetExportLinks retrieves all available export links for a Google Workspace document. This returns a map of MIME types to direct download URLs that can be used to download the document in various formats.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the Google Workspace document

Returns:

  • map[string]string: Map of MIME type to download URL
  • error: Error if file is not a Workspace document or API call fails

Example:

links, err := client.GetExportLinks(ctx, docID)
for mimeType, url := range links {
    fmt.Printf("%s: %s\n", mimeType, url)
}
// Output might be:
// application/pdf: https://docs.google.com/...
// application/vnd.openxmlformats-officedocument.wordprocessingml.document: https://docs.google.com/...

func (*DriveClient) IsWorkspaceDocument

func (dc *DriveClient) IsWorkspaceDocument(ctx context.Context, fileID string) (bool, error)

IsWorkspaceDocument checks if a file is a Google Workspace document. Returns true for Google Docs, Sheets, Slides, Forms, Drawings, etc. Returns false for regular files and folders.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file to check

Returns:

  • bool: true if file is a Google Workspace document, false otherwise
  • error: Any error encountered during the API call

Example:

isWorkspace, err := client.IsWorkspaceDocument(ctx, fileID)
if err != nil {
    log.Fatal(err)
}
if isWorkspace {
    // Use ExportWorkspaceDocument instead of DownloadFile
    client.ExportWorkspaceDocument(ctx, fileID, &buf, gdrive.ExportFormatPDF)
} else {
    // Regular file download
    client.DownloadFile(ctx, fileID, "output.bin")
}

func (*DriveClient) ListFiles

func (dc *DriveClient) ListFiles(ctx context.Context) ([]FileInfo, error)

ListFiles retrieves all non-folder files from Google Drive with folder path information. This method fetches files across all folders and computes the full folder path for each file. Files are retrieved in pages of MaxPageSize (100) items.

Note: This method skips:

  • Folders (mimeType: "application/vnd.google-apps.folder")
  • Zero-byte files (likely corrupted or placeholders)

Parameters:

  • ctx: Context for cancellation and timeout

Returns:

  • []FileInfo: Slice of file metadata with folder paths
  • error: Any error encountered during API calls

Example:

files, err := client.ListFiles(ctx)
for _, file := range files {
    fmt.Printf("%s (%d bytes) - %s\n", file.Name, file.Size, file.FolderPath)
}

func (*DriveClient) ListFilesInFolder

func (dc *DriveClient) ListFilesInFolder(ctx context.Context, parentFolderID string) ([]FileInfo, error)

ListFilesInFolder retrieves all non-folder files from a specific Google Drive folder. This method is more efficient than ListFiles when you only need files from one folder.

Parameters:

  • ctx: Context for cancellation and timeout
  • parentFolderID: ID of the parent folder. Empty string lists root-level files in "My Drive"

Returns:

  • []FileInfo: Slice of file metadata with folder paths
  • error: Any error encountered during API calls

Example:

// List files in a specific folder
files, err := client.ListFilesInFolder(ctx, "1aBc2DeFg3HiJ4KlM5nOp")

// List files in root of My Drive
files, err := client.ListFilesInFolder(ctx, "")

func (*DriveClient) PartialDownloadFile

func (dc *DriveClient) PartialDownloadFile(ctx context.Context, fileID string, w io.Writer, opts PartialDownloadOptions) (int64, error)

PartialDownloadFile downloads a specific byte range of a file from Google Drive. This is useful for resumable downloads, streaming large files in chunks, or implementing HTTP range requests.

Note: Partial downloads are not supported for Google Workspace documents (Google Docs, Sheets, Slides, etc.). Use ExportWorkspaceDocument instead.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file to download
  • w: Destination writer for the file content
  • opts: Byte range options specifying start and end positions

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during download

Example:

// Download first 1 MB
opts := gdrive.PartialDownloadOptions{StartByte: 0, EndByte: 1048575}
bytesWritten, err := client.PartialDownloadFile(ctx, fileID, &buf, opts)

// Resume download from byte 1048576
opts = gdrive.PartialDownloadOptions{StartByte: 1048576, EndByte: 2097151}
bytesWritten, err = client.PartialDownloadFile(ctx, fileID, &buf, opts)

func (*DriveClient) PartialDownloadRevision

func (dc *DriveClient) PartialDownloadRevision(ctx context.Context, fileID, revisionID string, w io.Writer, opts PartialDownloadOptions) (int64, error)

PartialDownloadRevision downloads a specific byte range of a file revision. The revision must be marked as "Keep Forever" in Google Drive to be downloadable. Useful for resumable downloads of historical file versions.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file
  • revisionID: ID of the specific revision to download
  • w: Destination writer for the revision content
  • opts: Byte range options specifying start and end positions

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during download

Example:

opts := gdrive.PartialDownloadOptions{StartByte: 0, EndByte: 1023}
bytesWritten, err := client.PartialDownloadRevision(ctx, fileID, revisionID, &buf, opts)

func (*DriveClient) PartialStreamFile

func (dc *DriveClient) PartialStreamFile(ctx context.Context, fileID string, w io.Writer, startByte, endByte int64) (int64, error)

PartialStreamFile is a convenience wrapper around PartialDownloadFile. Downloads a specific byte range of a file to the provided writer.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file to download
  • w: Destination writer for the file content
  • startByte: Starting byte position (inclusive, zero-based)
  • endByte: Ending byte position (inclusive)

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during download

Example:

// Download bytes 0-1023 (first 1024 bytes)
bytesWritten, err := client.PartialStreamFile(ctx, fileID, &buf, 0, 1023)

func (*DriveClient) RestoreFile

func (dc *DriveClient) RestoreFile(ctx context.Context, fileID string) error

RestoreFile restores a file or folder from the trash in Google Drive.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file or folder to restore

Returns:

  • error: Any error encountered during the operation

Example:

err := client.RestoreFile(ctx, "1aBc2DeF")

func (*DriveClient) StreamFile

func (dc *DriveClient) StreamFile(ctx context.Context, fileID string, w io.Writer) (int64, error)

StreamFile downloads a file from Google Drive and streams its content to the provided io.Writer. This is highly efficient for large files and web responses (e.g., http.ResponseWriter). The entire file content is copied to the writer without loading it into memory.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: Unique Google Drive file identifier
  • w: Destination writer (e.g., os.File, bytes.Buffer, http.ResponseWriter)

Returns:

  • int64: Number of bytes written
  • error: Any error encountered during download or streaming

Example:

// Stream to HTTP response
bytesWritten, err := client.StreamFile(ctx, fileID, w)

// Stream to buffer
var buf bytes.Buffer
bytesWritten, err := client.StreamFile(ctx, fileID, &buf)

func (*DriveClient) TrashFile

func (dc *DriveClient) TrashFile(ctx context.Context, fileID string) error

TrashFile moves a file or folder to the trash in Google Drive. Trashed items can be restored using RestoreFile or permanently deleted from the Google Drive web interface.

Parameters:

  • ctx: Context for cancellation and timeout
  • fileID: ID of the file or folder to trash

Returns:

  • error: Any error encountered during the operation

Example:

err := client.TrashFile(ctx, "1aBc2DeF")
if err != nil {
    log.Printf("Failed to trash file: %v", err)
}

func (*DriveClient) UploadFile

func (dc *DriveClient) UploadFile(ctx context.Context, filePath, fileName, parentFolderID string) (string, error)

UploadFile uploads a local file to Google Drive. The MIME type is automatically detected from the file content.

Parameters:

  • ctx: Context for cancellation and timeout
  • filePath: Path to the local file to upload
  • fileName: Display name in Google Drive. If empty, uses the basename of filePath
  • parentFolderID: ID of the parent folder. Empty string uploads to "My Drive" root

Returns:

  • string: File ID of the uploaded file in Google Drive
  • error: Any error encountered during upload

Example:

// Upload to root of My Drive
fileID, err := client.UploadFile(ctx, "/docs/report.pdf", "Q4 Report.pdf", "")

// Upload to specific folder
fileID, err := client.UploadFile(ctx, "/docs/report.pdf", "Q4 Report.pdf", "folderID123")

func (*DriveClient) UploadFileFromReader

func (dc *DriveClient) UploadFileFromReader(ctx context.Context, reader io.Reader, fileName, mimeType, parentFolderID string) (string, error)

UploadFileFromReader uploads a file to Google Drive from an io.Reader. This is particularly useful for web applications to upload files directly from HTTP requests without saving to disk first.

Parameters:

  • ctx: Context for cancellation and timeout
  • reader: Source reader containing file content
  • fileName: Display name in Google Drive (required)
  • mimeType: MIME type of the file. Use "application/octet-stream" if unknown
  • parentFolderID: ID of the parent folder. Empty string uploads to "My Drive" root

Returns:

  • string: File ID of the uploaded file in Google Drive
  • error: Any error encountered during upload

Example:

// Upload from HTTP request
file, header, _ := r.FormFile("upload")
defer file.Close()
fileID, err := client.UploadFileFromReader(ctx, file, header.Filename,
    header.Header.Get("Content-Type"), "")

type ExportFormat

type ExportFormat string

ExportFormat represents supported export formats for Google Workspace documents. Different document types support different export formats.

const (
	ExportFormatPDF  ExportFormat = "application/pdf"                                                           // PDF (all types)
	ExportFormatDOCX ExportFormat = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"   // Word (Docs)
	ExportFormatXLSX ExportFormat = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"         // Excel (Sheets)
	ExportFormatPPTX ExportFormat = "application/vnd.openxmlformats-officedocument.presentationml.presentation" // PowerPoint (Slides)
	ExportFormatODT  ExportFormat = "application/vnd.oasis.opendocument.text"                                   // OpenDocument Text (Docs)
	ExportFormatODS  ExportFormat = "application/vnd.oasis.opendocument.spreadsheet"                            // OpenDocument Spreadsheet (Sheets)
	ExportFormatODP  ExportFormat = "application/vnd.oasis.opendocument.presentation"                           // OpenDocument Presentation (Slides)
	ExportFormatRTF  ExportFormat = "application/rtf"                                                           // Rich Text Format (Docs)
	ExportFormatTXT  ExportFormat = "text/plain"                                                                // Plain text (Docs)
	ExportFormatHTML ExportFormat = "text/html"                                                                 // HTML (Docs, Sheets)
	ExportFormatZIP  ExportFormat = "application/zip"                                                           // ZIP (Docs, Sheets, Slides)
	ExportFormatJPEG ExportFormat = "image/jpeg"                                                                // JPEG (Drawings, Slides)
	ExportFormatPNG  ExportFormat = "image/png"                                                                 // PNG (Drawings, Slides)
	ExportFormatSVG  ExportFormat = "image/svg+xml"                                                             // SVG (Drawings)
	ExportFormatCSV  ExportFormat = "text/csv"                                                                  // CSV (Sheets)
	ExportFormatEPUB ExportFormat = "application/epub+zip"                                                      // EPUB (Docs)
)

Export format constants for Google Workspace documents.

type FileInfo

type FileInfo struct {
	ID          string   // Unique file identifier in Google Drive
	Name        string   // Display name of the file
	MimeType    string   // MIME type (e.g., "application/pdf", "image/jpeg")
	Size        int64    // Size in bytes (0 for Google Workspace documents)
	WebViewLink string   // URL to view the file in a browser
	Parents     []string // List of parent folder IDs
	FolderPath  string   // Full folder path (e.g., "My Drive/Projects/2024")
}

FileInfo represents metadata about a Google Drive file. This includes basic file information and the computed folder path.

type PartialDownloadOptions

type PartialDownloadOptions struct {
	StartByte int64 // Starting byte position (inclusive, zero-based)
	EndByte   int64 // Ending byte position (inclusive)
}

PartialDownloadOptions specifies options for downloading a specific byte range of a file. Useful for resumable downloads, streaming large files in chunks, or implementing range requests for media serving.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL