How to Use the Google Cloud Client Libraries for Go

Web
Initialize a Google Cloud client in Go by importing the specific service package, creating a client with context, and setting the GOOGLE_APPLICATION_CREDENTIALS environment variable.

Use the official Google Cloud Go client libraries by importing the specific service package, initializing a client with context, and calling the desired API method.

package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/storage"
)

func main() {
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Example: List buckets
	iter := client.Buckets(ctx, "my-project-id")
	for {
		attrs, err := iter.Next()
		if err == nil {
			fmt.Println(attrs.Name)
		} else {
			break
		}
	}
}

Ensure you have the GOOGLE_APPLICATION_CREDENTIALS environment variable set to your service account JSON file path before running.