Skip to content

Instantly share code, notes, and snippets.

@karalabe
Last active October 23, 2023 18:21
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save karalabe/8933476 to your computer and use it in GitHub Desktop.
Save karalabe/8933476 to your computer and use it in GitHub Desktop.
Access Google services through service accounts in Go
package main
import (
"code.google.com/p/goauth2/oauth/jwt"
"code.google.com/p/google-api-go-client/storage/v1beta2"
"fmt"
"log"
"regexp"
)
var serviceAccountEmail = "<project id>-<base64 string>@developer.gserviceaccount.com"
var serviceAccountKey = []byte(`<contents of your service account key file>`)
func main() {
// Create a new JWT token to authorize server-to-server Google Cloud Storage API calls
token := jwt.NewToken(serviceAccountEmail, storage.DevstorageRead_onlyScope, serviceAccountKey)
// Create an authenticated HTTP client (expired tokens get refreshed automatically)
transport, err := jwt.NewTransport(token)
if err != nil {
log.Fatalf("failed to create authenticated transport: %v.", err)
}
// Create the actual API connection to Google Cloud Storage
api, err := storage.New(transport.Client())
if err != nil {
log.Fatalf("failed to connect to Google Cloud Storage: %v.", err)
}
// ----- Execute some sample API call: list all the buckets in the project -----
// Get the project ID from the account email (numbers before the dash)
// You could hard code this, but why would you do that?
project := regexp.MustCompile("([0-9]+)-.+").FindStringSubmatch(serviceAccountEmail)[1]
// List all buckets within the projects storage
fmt.Printf("Buckets owned by project #%v:\n", project)
buckets, err := api.Buckets.List(project).Do()
if err != nil {
log.Fatalf("failed to retrieve bucket list: %v.", err)
}
for _, bucket := range buckets.Items {
fmt.Printf(" - %s\n", bucket.Name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment