go/google
go/google provides secure, platform-aware Google Workspace authenticator builders and client factory constructors optimized for high-throughput cloud-native Go microservices.
Packages
auth: Platform-aware Google OAuth2, Domain-Wide Delegation (DWD), Service Account Impersonation, and transient HTTP retry transports.
client: Convenience constructor factories for Google Drive, Admin SDK, Reports API, Cloud Resource Manager, and Service Usage.
resourcemanager: GCP Project provisioning, folder/organization hierarchy assignment, and Cloud Billing account association.
serviceusage: Batch GCP service API enablement and status verification.
workspace/drive: High-performance streaming scanner, Shared Drive lifecycle (CreateSharedDrive, FindSharedDriveByName, ListSharedDrives), folder operations (CreateFolder, FindFolder), safe parent file moving (MoveFile), trashing (TrashFile), and idempotent membership reconciliation (EnsureDriveMembership, RoleRank).
workspace/sheets: Declarative Google Sheets synchronization and creation engine featuring formula injection protection, typed cell constructors, declarative corporate themes (ThemeCorporateNavy, ThemeModernSlate, ThemeEmeraldForest, ThemeCleanMinimal), idempotent tab sync (ReplaceTab), struct reflection (FromStructs), and Google Drive folder placement.
Features
- Domain-Wide Delegation (DWD): Seamless OAuth2 impersonation of workspace users via target service accounts.
- Fail-Fast DWD Validation: Built-in
DWDValidator checking access rights and subject alignment immediately on startup.
- Service Account Impersonation: Direct, secure SA-to-SA credentials configuration.
- Interactive Consent Support: Desktop-oriented consent flow with customizable token caching policies.
- HTTP Transport Customization: Injects custom HTTP clients to control connection limits, timeouts, and mocks.
- Uniform Transient-Failure Retry: Every client resolved by
auth.ResolveClient routes HTTP traffic through a retrying transport (429/5xx with exponential backoff), so pagination crawls, downloads, and buffered uploads survive transient errors. Tune with auth.WithRetryAttempts, opt out with auth.WithoutRetry.
Installation
go get github.com/duizendstra/alexandria/go/google
Quick Start
1. Initializing an Authenticated Google Drive Service
package main
import (
"context"
"fmt"
"log"
"github.com/duizendstra/alexandria/go/google/auth"
"github.com/duizendstra/alexandria/go/google/client"
)
func main() {
ctx := context.Background()
// Build a fully-authenticated Google Drive API client using DWD
driveService, err := client.NewDriveService(ctx,
auth.WithDomainWideDelegation("service-account@my-project.gserviceaccount.com", "user@my-domain.com"),
auth.WithScopes("https://www.googleapis.com/auth/drive.readonly"),
)
if err != nil {
log.Fatalf("Failed to initialize Google Drive client: %v", err)
}
fmt.Printf("Successfully created Drive service: %s\n", driveService.BasePath)
}
2. Validating Domain-Wide Delegation on Startup
package main
import (
"context"
"fmt"
"log"
"github.com/duizendstra/alexandria/go/google/auth"
"github.com/duizendstra/alexandria/go/google/client"
)
func main() {
ctx := context.Background()
driveService, err := client.NewDriveService(ctx,
auth.WithDomainWideDelegation("service-account@my-project.gserviceaccount.com", "user@my-domain.com"),
auth.WithScopes("https://www.googleapis.com/auth/drive.readonly"),
)
if err != nil {
log.Fatalf("Failed to initialize client: %v", err)
}
// Create validator to verify access before handling requests.
// It validates the delegated subject the service credentials were
// built with (user@my-domain.com above).
validator := auth.NewDWDValidator(driveService)
if err := validator.ValidateAccess(ctx); err != nil {
log.Fatalf("DWD access check failed: %v", err)
}
fmt.Println("DWD access verified successfully")
}
3. Declarative Google Sheets Synchronization
package main
import (
"context"
"fmt"
"log"
"github.com/duizendstra/alexandria/go/google/auth"
"github.com/duizendstra/alexandria/go/google/client"
"github.com/duizendstra/alexandria/go/google/workspace/sheets"
)
type MigrationStatus struct {
Account string `sheets:"Source Account,minWidth=200,maxWidth=350"`
Status string `sheets:"Status,width=120"`
AuditLink sheets.Cell `sheets:"Audit Log,width=250"`
}
func main() {
ctx := context.Background()
// Build a fully-authenticated Sheets service
sheetsSvc, err := client.NewSheetsService(ctx, sheets.Config{},
auth.WithDomainWideDelegation("sa@project.gserviceaccount.com", "admin@domain.com"),
)
if err != nil {
log.Fatalf("Failed to initialize Sheets service: %v", err)
}
table, err := sheets.FromStructs([]MigrationStatus{
{
Account: "user1@domain.com",
Status: "MIGRATED",
AuditLink: sheets.Hyperlink("https://console.cloud.google.com", "View Log"),
},
})
if err != nil {
log.Fatalf("Table error: %v", err)
}
result, err := sheetsSvc.ReplaceTab(ctx, "my-spreadsheet-id", sheets.TabSpec{
Title: "Wave 1",
Theme: sheets.ThemeCorporateNavy(),
Data: table,
})
if err != nil {
log.Fatalf("Sync error: %v", err)
}
fmt.Printf("Tab synchronized: %s (%d rows written)\n", result.Title, result.RowsWritten)
}
- Fail-Fast Verification: The
DWDValidator validates authentication scopes and user delegation policies at startup, preventing cascading logical failures inside application hotpaths.
- Connection Pooling Preservation: Custom HTTP client injection via
WithHTTPClient lets services inject clients configured with specialized idle connection limits, preventing connection starvation.
- Impersonation Token Reuse: Resolves access token generation using Google's native IAM credentials flow, avoiding hardcoded long-lived private keys.
Consumers & Load-Bearing Promises
Consumer Archetypes
- Workspace automation: tools acting on Drive or Sheets as a delegated
identity rather than as themselves.
- Project provisioning: work creating or configuring GCP projects and the
APIs enabled on them.
Load-Bearing Promises
- A Client Is Validated Before It Is Handed Out: configuration and the
delegation subject are checked at resolve time, so a misconfigured client
fails where it is built rather than at the first call.
- Delegated Access Is Verified, Not Assumed: domain-wide delegation is
validated against the subject being impersonated before the caller relies
on it.
- Resolved Clients Carry Retry: the transport handed back already applies
the retry classification, so a caller does not have to remember to wrap it.
- Interactive Consent Opens Safely: the browser handoff refuses to launch
anything other than the intended consent URL.
- Sheets Rendering Is Stable: a table built from structs keeps its column
ordering and named column widths, a hyperlink without a label falls back to
a readable one, and replacing a tab creates it when missing rather than
erroring.