### Connect with Go Source: https://localgcp.com/docs/memorystore.html Example demonstrating how to set and get keys using the go-redis/v9 client. ```go package main import ( "context" "fmt" "log" "github.com/redis/go-redis/v9" ) func main() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) defer rdb.Close() // SET a key err := rdb.Set(ctx, "greeting", "hello from localgcp", 0).Err() if err != nil { log.Fatal(err) } // GET the key val, err := rdb.Get(ctx, "greeting").Result() if err != nil { log.Fatal(err) } fmt.Println(val) // "hello from localgcp" } ``` -------------------------------- ### Install from source Source: https://localgcp.com/docs Install the latest version directly using the Go toolchain. ```bash $ go install github.com/slokam-ai/localgcp/cmd/localgcp@latest ``` -------------------------------- ### Install and Start Ollama Source: https://localgcp.com/docs/vertex-ai.html Commands to install the Ollama CLI, start the server, and pull a local model. ```bash $ brew install ollama # or download from ollama.com $ ollama serve # start the Ollama server $ ollama pull gemma3 # pull a model ``` -------------------------------- ### Connect with Python Source: https://localgcp.com/docs/memorystore.html Example demonstrating how to set and get keys using the redis-py client. ```python import redis r = redis.Redis(host="localhost", port=6379) r.set("greeting", "hello from localgcp") print(r.get("greeting")) # b"hello from localgcp" ``` -------------------------------- ### Start the emulator Source: https://localgcp.com/docs Launch all native services in the foreground. ```bash $ localgcp up ``` -------------------------------- ### Connect with Go Source: https://localgcp.com/docs/cloud-sql.html Example using database/sql and the lib/pq driver to connect to the local instance. ```go package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres dbname=localgcp sslmode=disable", ) if err != nil { log.Fatal(err) } defer db.Close() if err := db.Ping(); err != nil { log.Fatal(err) } fmt.Println("connected to Cloud SQL (localgcp)") } ``` -------------------------------- ### Start with custom configuration Source: https://localgcp.com/docs Launch the emulator with specific data directories, port overrides, and service mappings. ```bash $ localgcp up \ --data-dir=./.localgcp \ --port-gcs=4443 \ --port-pubsub=8085 \ --port-secretmanager=8086 \ --port-firestore=8088 \ --port-cloudtasks=8089 \ --port-vertexai=8090 \ --port-kms=8091 \ --port-logging=8092 \ --port-cloudrun=8093 \ --services=spanner,bigtable,cloudsql,memorystore \ --ollama-host=http://localhost:11434 \ --vertex-model-map="gemini-2.5-flash=gemma3" \ --quiet ``` -------------------------------- ### Install via Homebrew Source: https://localgcp.com/docs Recommended installation method for macOS and Linux users. ```bash $ brew install slokam-ai/tap/localgcp ``` -------------------------------- ### Start BigQuery Service Source: https://localgcp.com/docs/bigquery.html Use the localgcp CLI to initialize the BigQuery service container. ```bash $ localgcp up --services=bigquery ``` -------------------------------- ### Start Spanner Emulator Source: https://localgcp.com/docs/spanner.html Use the localgcp CLI to initialize the Spanner service. ```bash $ localgcp up --services=spanner ``` -------------------------------- ### Start Memorystore Service Source: https://localgcp.com/docs/memorystore.html Command to initialize the Memorystore service using the localgcp CLI. ```bash $ localgcp up --services=memorystore ``` -------------------------------- ### Verify localgcp installation with smoketest Source: https://localgcp.com/docs Use the built-in smoketest binary to confirm all services are operational after starting the environment. ```bash $ localgcp up & $ eval $(localgcp env) # Run the smoketest binary $ ./smoketest ``` -------------------------------- ### Connect and Query Spanner in Go Source: https://localgcp.com/docs/spanner.html Example demonstrating how to configure the Go SDK to point to the local emulator, create an instance and database, and perform CRUD operations. ```go package main import ( "context" "fmt" "log" "os" spanner "cloud.google.com/go/spanner" database "cloud.google.com/go/spanner/admin/database/apiv1" databasepb "cloud.google.com/go/spanner/admin/database/apiv1/databasepb" instance "cloud.google.com/go/spanner/admin/instance/apiv1" instancepb "cloud.google.com/go/spanner/admin/instance/apiv1/instancepb" "google.golang.org/api/iterator" ) func main() { // Point the SDK at the localgcp emulator os.Setenv("SPANNER_EMULATOR_HOST", "localhost:9010") ctx := context.Background() project := "my-project" // Create an instance instanceAdmin, err := instance.NewInstanceAdminClient(ctx) if err != nil { log.Fatal(err) } defer instanceAdmin.Close() op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{ Parent: fmt.Sprintf("projects/%s", project), InstanceId: "my-instance", Instance: &instancepb.Instance{ DisplayName: "My Instance", Config: fmt.Sprintf("projects/%s/instanceConfigs/emulator-config", project), NodeCount: 1, }, }) if err != nil { log.Fatal(err) } if _, err = op.Wait(ctx); err != nil { log.Fatal(err) } // Create a database with a table databaseAdmin, err := database.NewDatabaseAdminClient(ctx) if err != nil { log.Fatal(err) } defer databaseAdmin.Close() dbOp, err := databaseAdmin.CreateDatabase(ctx, &databasepb.CreateDatabaseRequest{ Parent: fmt.Sprintf("projects/%s/instances/my-instance", project), CreateStatement: "CREATE DATABASE `my-db`", ExtraStatements: []string{ `CREATE TABLE Users ( UserId INT64 NOT NULL, Name STRING(1024), Email STRING(1024), ) PRIMARY KEY (UserId)`, }, }) if err != nil { log.Fatal(err) } if _, err = dbOp.Wait(ctx); err != nil { log.Fatal(err) } // Insert a row and query it db := fmt.Sprintf("projects/%s/instances/my-instance/databases/my-db", project) client, err := spanner.NewClient(ctx, db) if err != nil { log.Fatal(err) } defer client.Close() _, err = client.Apply(ctx, []*spanner.Mutation{ spanner.InsertOrUpdate("Users", []string{"UserId", "Name", "Email"}, []interface{}{1, "Alice", "alice@example.com"}, ), }) if err != nil { log.Fatal(err) } iter := client.Single().Query(ctx, spanner.Statement{ SQL: "SELECT UserId, Name, Email FROM Users", }) defer iter.Stop() for { row, err := iter.Next() if err == iterator.Done { break } if err != nil { log.Fatal(err) } var userId int64 var name, email string if err := row.Columns(&userId, &name, &email); err != nil { log.Fatal(err) } fmt.Printf("User: %d %s %s\n", userId, name, email) } } ``` -------------------------------- ### Start Bigtable service Source: https://localgcp.com/docs/bigtable.html Use the localgcp CLI to start the Bigtable emulator service. ```bash $ localgcp up --services=bigtable ``` -------------------------------- ### Connect and interact with Bigtable in Go Source: https://localgcp.com/docs/bigtable.html Example demonstrating how to configure the Go SDK to point to the local emulator, create a table, and perform basic read/write operations. ```go package main import ( "context" "fmt" "log" "os" bigtable "cloud.google.com/go/bigtable" ) func main() { // Point the SDK at localgcp os.Setenv("BIGTABLE_EMULATOR_HOST", "localhost:9094") ctx := context.Background() project := "my-project" instance := "my-instance" // Admin client -- create table and column family admin, err := bigtable.NewAdminClient(ctx, project, instance) if err != nil { log.Fatal(err) } defer admin.Close() if err := admin.CreateTable(ctx, "my-table"); err != nil { log.Fatal(err) } if err := admin.CreateColumnFamily(ctx, "my-table", "cf1"); err != nil { log.Fatal(err) } // Data client -- write and read client, err := bigtable.NewClient(ctx, project, instance) if err != nil { log.Fatal(err) } defer client.Close() tbl := client.Open("my-table") // Write a row mut := bigtable.NewMutation() mut.Set("cf1", "greeting", bigtable.Now(), []byte("Hello, localgcp!")) if err := tbl.Apply(ctx, "row-1", mut); err != nil { log.Fatal(err) } // Read it back row, err := tbl.ReadRow(ctx, "row-1") if err != nil { log.Fatal(err) } fmt.Printf("Row: %s\n", row["cf1"][0].Value) } ``` -------------------------------- ### Start Cloud SQL service Source: https://localgcp.com/docs/cloud-sql.html Command to initialize the Cloud SQL container using localgcp. ```bash $ localgcp up --services=cloudsql ``` -------------------------------- ### Connect with Python Source: https://localgcp.com/docs/cloud-sql.html Example using the psycopg2 library to establish a connection and execute a query. ```python import psycopg2 conn = psycopg2.connect( host="localhost", port=5432, user="postgres", dbname="localgcp", ) cur = conn.cursor() cur.execute("SELECT 1") print(cur.fetchone()) conn.close() ``` -------------------------------- ### Go SDK Cloud Storage Operations Source: https://localgcp.com/docs/cloud-storage.html Example demonstrating bucket creation, object upload, and object download using the official Go client library. ```go package main import ( "context" "fmt" "io" "log" "cloud.google.com/go/storage" ) func main() { ctx := context.Background() // STORAGE_EMULATOR_HOST=localhost:4443 must be set client, err := storage.NewClient(ctx) if err != nil { log.Fatal(err) } defer client.Close() bucket := client.Bucket("my-bucket") // Create bucket if err := bucket.Create(ctx, "my-project", nil); err != nil { log.Fatal(err) } // Upload an object w := bucket.Object("hello.txt").NewWriter(ctx) fmt.Fprint(w, "Hello, localgcp!") if err := w.Close(); err != nil { log.Fatal(err) } // Download the object r, err := bucket.Object("hello.txt").NewReader(ctx) if err != nil { log.Fatal(err) } defer r.Close() data, _ := io.ReadAll(r) fmt.Println(string(data)) // "Hello, localgcp!" } ``` -------------------------------- ### Configure Vertex AI Emulator via CLI Source: https://localgcp.com/docs/vertex-ai.html Start the local emulator with custom Ollama host and model mapping configurations. ```bash $ localgcp up \ --ollama-host=http://localhost:11434 \ --vertex-model-map="gemini-2.5-flash=llama3.2,text-embedding-004=nomic-embed-text" ``` -------------------------------- ### Enable Data Persistence Source: https://localgcp.com/docs/cloud-storage.html Start the emulator with a data directory to persist storage state across restarts. ```bash $ localgcp up --data-dir=./.localgcp ``` -------------------------------- ### Start with orchestrated services Source: https://localgcp.com/docs Enable additional services like Spanner and Bigtable via Docker containers. ```bash # Add Spanner and Bigtable $ localgcp up --services=spanner,bigtable # Add all four orchestrated services $ localgcp up --services=spanner,bigtable,cloudsql,memorystore ``` -------------------------------- ### Generate embeddings with Go SDK Source: https://localgcp.com/docs/vertex-ai.html Example of initializing the Vertex AI client and requesting content embeddings via the Go SDK. ```go package main import ( "context" "fmt" "log" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ Project: "my-project", Location: "us-central1", Backend: genai.BackendVertexAI, HTTPOptions: genai.HTTPOptions{ BaseURL: "http://localhost:8090", }, }) if err != nil { log.Fatal(err) } resp, err := client.Models.EmbedContent(ctx, "text-embedding-004", genai.Text("What is the meaning of life?"), nil, ) if err != nil { log.Fatal(err) } fmt.Printf("Embedding dimensions: %d\n", len(resp.Embeddings[0].Values)) // Proxied to nomic-embed-text via Ollama } ``` -------------------------------- ### Firestore Query Operators Source: https://localgcp.com/docs/firestore.html Examples of advanced query operators supported by the emulator. ```go // IN query client.Collection("users").Where("name", "in", []string{"Alice", "Bob"}) // ARRAY_CONTAINS client.Collection("users").Where("tags", "array-contains", "admin") // ARRAY_CONTAINS_ANY client.Collection("users").Where("tags", "array-contains-any", []string{"admin", "ops"}) // NOT_IN client.Collection("users").Where("name", "not-in", []string{"Charlie"}) ``` -------------------------------- ### Reinstall localgcp via Homebrew Source: https://localgcp.com/docs Update the localgcp formula to version 0.5.1 or later to resolve installation issues. ```bash $ brew untap slokam-ai/tap 2>/dev/null $ brew tap slokam-ai/tap $ brew install slokam-ai/tap/localgcp ``` -------------------------------- ### Bypass macOS Gatekeeper quarantine Source: https://localgcp.com/docs Use this command if macOS prevents the localgcp binary from executing after installation. ```bash $ xattr -d com.apple.quarantine $(which localgcp) ``` -------------------------------- ### Create Queue and Task with Go SDK Source: https://localgcp.com/docs/cloud-tasks.html Demonstrates connecting to the local emulator, creating a queue, and scheduling an HTTP task. ```go package main import ( "context" "fmt" "log" cloudtasks "cloud.google.com/go/cloudtasks/apiv2" taskspb "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb" "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/types/known/timestamppb" "time" ) func main() { ctx := context.Background() // Connect to localgcp (no TLS, no auth) client, err := cloudtasks.NewClient(ctx, option.WithEndpoint("localhost:8089"), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithTransportCredentials( insecure.NewCredentials(), )), ) if err != nil { log.Fatal(err) } defer client.Close() parent := "projects/my-project/locations/us-central1" // Create a queue queue, err := client.CreateQueue(ctx, &taskspb.CreateQueueRequest{ Parent: parent, Queue: &taskspb.Queue{ Name: parent + "/queues/my-queue", }, }) if err != nil { log.Fatal(err) } // Create a task with an HTTP target task, err := client.CreateTask(ctx, &taskspb.CreateTaskRequest{ Parent: queue.Name, Task: &taskspb.Task{ MessageType: &taskspb.Task_HttpRequest{ HttpRequest: &taskspb.HttpRequest{ Url: "http://localhost:9000/process", HttpMethod: taskspb.HttpMethod_POST, Body: []byte(`{"order_id": "12345"}`), Headers: map[string]string{"Content-Type": "application/json"}, }, }, // Optional: schedule for later ScheduleTime: timestamppb.New(time.Now().Add(30 * time.Second)), }, }) if err != nil { log.Fatal(err) } fmt.Printf("Created task: %s\n", task.Name) } ``` -------------------------------- ### Pub/Sub Go SDK Operations Source: https://localgcp.com/docs/pubsub.html Demonstrates creating a topic, creating a subscription, publishing a message, and receiving it using the Go client library. ```go package main import ( "context" "fmt" "log" "time" "cloud.google.com/go/pubsub" ) func main() { ctx := context.Background() // PUBSUB_EMULATOR_HOST=localhost:8085 must be set client, err := pubsub.NewClient(ctx, "my-project") if err != nil { log.Fatal(err) } defer client.Close() // Create a topic topic, err := client.CreateTopic(ctx, "my-topic") if err != nil { log.Fatal(err) } // Create a subscription sub, err := client.CreateSubscription(ctx, "my-sub", pubsub.SubscriptionConfig{ Topic: topic, }) if err != nil { log.Fatal(err) } // Publish a message result := topic.Publish(ctx, &pubsub.Message{ Data: []byte("Hello, Pub/Sub!"), Attributes: map[string]string{"env": "local"}, }) id, err := result.Get(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Published message ID: %s\n", id) // Receive messages ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() err = sub.Receive(ctx, func(_ context.Context, msg *pubsub.Message) { fmt.Printf("Received: %s\n", msg.Data) msg.Ack() cancel() // stop after first message }) if err != nil && err != context.Canceled { log.Fatal(err) } } ``` -------------------------------- ### Configure Vertex AI SDK for Local Development Source: https://localgcp.com/docs/vertex-ai.html Demonstrates how to use the same genai client configuration for both production and local development by modifying the BaseURL. ```go // Production: hits Vertex AI on Google Cloud client, _ := genai.NewClient(ctx, prodConfig) resp, _ := client.Models.GenerateContent(ctx, "gemini-2.5-flash", prompt, nil) // Local dev: hits localgcp -> Ollama -> Gemma running on your laptop client, _ := genai.NewClient(ctx, localConfig) // only BaseURL differs resp, _ := client.Models.GenerateContent(ctx, "gemini-2.5-flash", prompt, nil) ``` -------------------------------- ### Generate Content with Go SDK Source: https://localgcp.com/docs/vertex-ai.html Initialize the Vertex AI client pointing to the local emulator and generate content using a mapped model. ```go package main import ( "context" "fmt" "log" "google.golang.org/genai" ) func main() { ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ Project: "my-project", Location: "us-central1", Backend: genai.BackendVertexAI, HTTPOptions: genai.HTTPOptions{ BaseURL: "http://localhost:8090", }, }) if err != nil { log.Fatal(err) } resp, err := client.Models.GenerateContent(ctx, "gemini-2.5-flash", genai.Text("Explain quantum computing in one sentence"), nil, ) if err != nil { log.Fatal(err) } fmt.Println(resp.Candidates[0].Content.Parts[0].Text) // Response comes from Ollama (e.g. llama3.2) running locally } ``` -------------------------------- ### Switch to Production Source: https://localgcp.com/docs/bigquery.html Revert configuration to use production Google Cloud services. ```bash $ unset CLOUDSDK_API_ENDPOINT_OVERRIDES_BIGQUERY ``` ```python import os endpoint = os.environ.get("LOCALBQ_ENDPOINT") if endpoint: client = bigquery.Client( project="my-project", credentials=AnonymousCredentials(), client_options={"api_endpoint": endpoint}, ) else: client = bigquery.Client(project="my-project") ``` -------------------------------- ### Write and list log entries with Go SDK Source: https://localgcp.com/docs/cloud-logging.html Connects to the localgcp emulator using insecure credentials and demonstrates writing log entries with severity levels and filtering them. ```go package main import ( "context" "fmt" "log" logging "cloud.google.com/go/logging/apiv2" loggingpb "cloud.google.com/go/logging/apiv2/loggingpb" "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ltype "google.golang.org/genproto/googleapis/logging/type" monitoredres "google.golang.org/genproto/googleapis/api/monitoredres" ) func main() { ctx := context.Background() // Connect to localgcp (no TLS, no auth) client, err := logging.NewClient(ctx, option.WithEndpoint("localhost:8092"), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithTransportCredentials( insecure.NewCredentials(), )), ) if err != nil { log.Fatal(err) } defer client.Close() project := "projects/my-project" // Write log entries with severity err = client.WriteLogEntries(ctx, &loggingpb.WriteLogEntriesRequest{ LogName: project + "/logs/my-service", Resource: &monitoredres.MonitoredResource{ Type: "global", Labels: map[string]string{ "project_id": "my-project", }, }, Entries: []*loggingpb.LogEntry{ { Severity: ltype.LogSeverity_INFO, Payload: &loggingpb.LogEntry_TextPayload{ TextPayload: "Server started on port 8080", }, Labels: map[string]string{ "env": "dev", }, }, { Severity: ltype.LogSeverity_ERROR, Payload: &loggingpb.LogEntry_TextPayload{ TextPayload: "Connection refused: database unreachable", }, }, }, }) if err != nil { log.Fatal(err) } // List entries with a filter (e.g. only errors) it := client.ListLogEntries(ctx, &loggingpb.ListLogEntriesRequest{ ResourceNames: []string{project}, Filter: "severity >= ERROR", }) for { entry, err := it.Next() if err != nil { break } fmt.Printf("[%s] %s\n", entry.Severity, entry.GetTextPayload()) } } ``` -------------------------------- ### Configure Pub/Sub Emulator Host Source: https://localgcp.com/docs/pubsub.html Set the environment variable to point client libraries to the local emulator. ```bash $ export PUBSUB_EMULATOR_HOST=localhost:8085 # or use: eval $(localgcp env) ``` -------------------------------- ### Firestore Go SDK CRUD and Query Operations Source: https://localgcp.com/docs/firestore.html Demonstrates initializing a client, creating a document, reading it, and performing a filtered query. ```go package main import ( "context" "fmt" "log" "cloud.google.com/go/firestore" ) func main() { ctx := context.Background() // FIRESTORE_EMULATOR_HOST=localhost:8088 must be set client, err := firestore.NewClient(ctx, "my-project") if err != nil { log.Fatal(err) } defer client.Close() // Create a document _, err = client.Collection("users").Doc("alice").Set(ctx, map[string]interface{}{ "name": "Alice", "age": 30, "tags": []string{"admin", "dev"}, }) if err != nil { log.Fatal(err) } // Read it back doc, err := client.Collection("users").Doc("alice").Get(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Name: %s\n", doc.Data()["name"]) // Query: find users older than 25 iter := client.Collection("users"). Where("age", ">", 25). OrderBy("age", firestore.Asc). Documents(ctx) defer iter.Stop() for { doc, err := iter.Next() if err != nil { break } fmt.Printf(" %s (age %v)\n", doc.Data()["name"], doc.Data()["age"]) } } ``` -------------------------------- ### Configure Cloud Storage Emulator Host Source: https://localgcp.com/docs/cloud-storage.html Set the environment variable to point client libraries to the local emulator. ```bash $ export STORAGE_EMULATOR_HOST=localhost:4443 # or use: eval $(localgcp env) ``` -------------------------------- ### Pre-fetch emulator image Source: https://localgcp.com/docs/bigtable.html Pull the required Docker image manually to avoid cold-start delays. ```bash $ docker pull google/cloud-sdk:emulators ``` -------------------------------- ### Connect via psql Source: https://localgcp.com/docs/cloud-sql.html Standard command to connect to the local Cloud SQL instance using the psql client. ```bash $ psql -h localhost -p 5432 -U postgres -d localgcp ``` -------------------------------- ### Connect with Python Source: https://localgcp.com/docs/bigquery.html Initialize a BigQuery client using anonymous credentials and a custom API endpoint. ```python from google.cloud import bigquery from google.auth.credentials import AnonymousCredentials client = bigquery.Client( project="my-project", credentials=AnonymousCredentials(), client_options={"api_endpoint": "http://localhost:9060"}, ) rows = client.query("SELECT 1 + 1 AS result").result() for row in rows: print(row.result) # 2 ``` -------------------------------- ### Connect and Manage Secrets in Go Source: https://localgcp.com/docs/secret-manager.html Demonstrates connecting to the local emulator and performing basic CRUD operations on secrets and versions. ```go package main import ( "context" "fmt" "log" secretmanager "cloud.google.com/go/secretmanager/apiv1" smpb "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { ctx := context.Background() // Connect to localgcp (no TLS, no auth) client, err := secretmanager.NewClient(ctx, option.WithEndpoint("localhost:8086"), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithTransportCredentials( insecure.NewCredentials(), )), ) if err != nil { log.Fatal(err) } defer client.Close() project := "projects/my-project" // Create a secret secret, err := client.CreateSecret(ctx, &smpb.CreateSecretRequest{ Parent: project, SecretId: "db-password", Secret: &smpb.Secret{ Replication: &smpb.Replication{ Replication: &smpb.Replication_Automatic_{ Automatic: &smpb.Replication_Automatic{}, }, }, }, }) if err != nil { log.Fatal(err) } // Add a version with the secret value version, err := client.AddSecretVersion(ctx, &smpb.AddSecretVersionRequest{ Parent: secret.Name, Payload: &smpb.SecretPayload{Data: []byte("s3cret-p@ss")}, }) if err != nil { log.Fatal(err) } // Access the secret (by version or "latest") resp, err := client.AccessSecretVersion(ctx, &smpb.AccessSecretVersionRequest{ Name: version.Name, // or: secret.Name + "/versions/latest" }) if err != nil { log.Fatal(err) } fmt.Printf("Secret: %s\n", resp.Payload.Data) } ``` -------------------------------- ### Verify Cloud Storage with Go Source: https://localgcp.com/docs A Go program to verify that the Cloud Storage emulator is responding correctly using the STORAGE_EMULATOR_HOST environment variable. ```go package main import ( "context" "fmt" "cloud.google.com/go/storage" ) func main() { ctx := context.Background() // STORAGE_EMULATOR_HOST is set by `localgcp env` client, err := storage.NewClient(ctx) if err != nil { panic(err) } defer client.Close() // Create a test bucket err = client.Bucket("test-bucket").Create(ctx, "my-project", nil) if err != nil { panic(err) } fmt.Println("localgcp is working!") } ``` -------------------------------- ### Run via Docker Source: https://localgcp.com/docs Execute the emulator using a Docker container with necessary port mappings. ```bash $ docker run --rm \ -p 4443:4443 -p 8085:8085 -p 8086:8086 \ -p 8088:8088 -p 8089:8089 -p 8090:8090 \ -p 8091:8091 -p 8092:8092 -p 8093:8093 \ ghcr.io/slokam-ai/localgcp ``` -------------------------------- ### Configure data persistence Source: https://localgcp.com/docs Enable persistent storage for supported services by specifying a data directory. ```bash $ localgcp up --data-dir=./.localgcp --services=cloudsql,memorystore,bigquery ``` -------------------------------- ### Connect application to emulators Source: https://localgcp.com/docs Set environment variables for GCP client libraries to automatically connect to local emulators. ```bash $ eval $(localgcp env) $ go run ./your-app ``` -------------------------------- ### Create Push Subscription Source: https://localgcp.com/docs/pubsub.html Configures a subscription to deliver messages via HTTP POST to a specified endpoint. ```go // Create a push subscription sub, err := client.CreateSubscription(ctx, "my-push-sub", pubsub.SubscriptionConfig{ Topic: topic, PushConfig: pubsub.PushConfig{ Endpoint: "http://localhost:9000/webhook", }, }) ``` -------------------------------- ### Set emulator environment variable Source: https://localgcp.com/docs/bigtable.html Configure the SDK to connect to the local emulator by setting the host environment variable. ```bash $ export BIGTABLE_EMULATOR_HOST=localhost:9094 ``` -------------------------------- ### Pre-fetch Emulator Image Source: https://localgcp.com/docs/spanner.html Commands to pull the Spanner emulator image to avoid cold-start delays. ```bash $ localgcp pull ``` ```bash $ docker pull gcr.io/cloud-spanner-emulator/emulator:1.5.23 ``` -------------------------------- ### Cloud KMS Go SDK Operations Source: https://localgcp.com/docs/cloud-kms.html Demonstrates creating a key ring and symmetric crypto key, followed by encryption and decryption operations using the Go SDK. ```go package main import ( "context" "encoding/base64" "fmt" "log" kms "cloud.google.com/go/kms/apiv1" kmspb "cloud.google.com/go/kms/apiv1/kmspb" "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { ctx := context.Background() // Connect to localgcp (no TLS, no auth) client, err := kms.NewKeyManagementClient(ctx, option.WithEndpoint("localhost:8091"), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithTransportCredentials( insecure.NewCredentials(), )), ) if err != nil { log.Fatal(err) } defer client.Close() location := "projects/my-project/locations/us-east1" // Create a key ring keyRing, err := client.CreateKeyRing(ctx, &kmspb.CreateKeyRingRequest{ Parent: location, KeyRingId: "my-key-ring", }) if err != nil { log.Fatal(err) } // Create a symmetric encrypt/decrypt key key, err := client.CreateCryptoKey(ctx, &kmspb.CreateCryptoKeyRequest{ Parent: keyRing.Name, CryptoKeyId: "my-symmetric-key", CryptoKey: &kmspb.CryptoKey{ Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT, VersionTemplate: &kmspb.CryptoKeyVersionTemplate{ Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION, }, }, }) if err != nil { log.Fatal(err) } // Encrypt encResp, err := client.Encrypt(ctx, &kmspb.EncryptRequest{ Name: key.Name, Plaintext: []byte("hello, localgcp"), }) if err != nil { log.Fatal(err) } fmt.Printf("Ciphertext: %s\n", base64.StdEncoding.EncodeToString(encResp.Ciphertext)) // Decrypt decResp, err := client.Decrypt(ctx, &kmspb.DecryptRequest{ Name: key.Name, Ciphertext: encResp.Ciphertext, }) if err != nil { log.Fatal(err) } fmt.Printf("Plaintext: %s\n", decResp.Plaintext) } ``` -------------------------------- ### Configure Firestore Emulator Host Source: https://localgcp.com/docs/firestore.html Set the environment variable to point client libraries to the local emulator. ```bash $ export FIRESTORE_EMULATOR_HOST=localhost:8088 # or use: eval $(localgcp env) ``` -------------------------------- ### Pre-fetch Docker images Source: https://localgcp.com/docs Reduce initial connection latency by pulling service images before they are needed. ```bash # Pull all orchestrated service images $ localgcp pull # Or pull specific services only $ localgcp pull --services=spanner,cloudsql ``` -------------------------------- ### Connect with bq CLI Source: https://localgcp.com/docs/bigquery.html Configure the bq CLI to point to the local service endpoint instead of the production Google Cloud API. ```bash $ export CLOUDSDK_API_ENDPOINT_OVERRIDES_BIGQUERY=http://localhost:9060/ $ bq --project_id=my-project query --use_legacy_sql=false 'SELECT 1 + 1 AS result' ``` -------------------------------- ### Initialize localgcp Environment Variables Source: https://localgcp.com/docs/spanner.html Automatically sets all necessary environment variables for localgcp. ```bash $ eval $(localgcp env) ``` -------------------------------- ### Set Spanner Emulator Host Environment Variable Source: https://localgcp.com/docs/spanner.html Configures the client library to point to the local emulator instance. ```bash $ export SPANNER_EMULATOR_HOST=localhost:9010 ``` -------------------------------- ### Connect via Redis CLI Source: https://localgcp.com/docs/memorystore.html Standard command to connect to the local Redis instance using redis-cli. ```bash $ redis-cli -h localhost -p 6379 ``` -------------------------------- ### Handle Dispatched HTTP Tasks Source: https://localgcp.com/docs/cloud-tasks.html A simple HTTP server implementation to receive and process tasks dispatched by the emulator. ```go // Simple task handler http.HandleFunc("/process", func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) fmt.Printf("Task received: %s\n", body) w.WriteHeader(http.StatusOK) }) http.ListenAndServe(":9000", nil) ``` -------------------------------- ### Connect and Manage Cloud Run Services in Go Source: https://localgcp.com/docs/cloud-run.html Connects to the localgcp emulator using insecure credentials and performs basic CRUD operations on services. ```go package main import ( "context" "fmt" "log" run "cloud.google.com/go/run/apiv2" runpb "cloud.google.com/go/run/apiv2/runpb" "google.golang.org/api/option" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { ctx := context.Background() // Connect to localgcp (no TLS, no auth) client, err := run.NewServicesClient(ctx, option.WithEndpoint("localhost:8093"), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithTransportCredentials( insecure.NewCredentials(), )), ) if err != nil { log.Fatal(err) } defer client.Close() parent := "projects/my-project/locations/us-central1" // Create a service (returns a long-running operation) // In localgcp the operation completes immediately -- no polling needed op, err := client.CreateService(ctx, &runpb.CreateServiceRequest{ Parent: parent, ServiceId: "my-service", Service: &runpb.Service{}, }) if err != nil { log.Fatal(err) } svc, err := op.Wait(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Created: %s\n", svc.Name) // Get the service svc, err = client.GetService(ctx, &runpb.GetServiceRequest{ Name: parent + "/services/my-service", }) if err != nil { log.Fatal(err) } fmt.Printf("URI: %s\n", svc.Uri) // List services iter := client.ListServices(ctx, &runpb.ListServicesRequest{ Parent: parent, }) for { s, err := iter.Next() if err != nil { break } fmt.Printf("Service: %s\n", s.Name) } // Delete the service delOp, err := client.DeleteService(ctx, &runpb.DeleteServiceRequest{ Name: parent + "/services/my-service", }) if err != nil { log.Fatal(err) } _, err = delOp.Wait(ctx) if err != nil { log.Fatal(err) } fmt.Println("Deleted.") } ``` -------------------------------- ### Manage Secret Version States in Go Source: https://localgcp.com/docs/secret-manager.html Shows how to programmatically disable, enable, or destroy a specific secret version. ```go // Disable a version _, err = client.DisableSecretVersion(ctx, &smpb.DisableSecretVersionRequest{ Name: secret.Name + "/versions/1", }) // Re-enable it _, err = client.EnableSecretVersion(ctx, &smpb.EnableSecretVersionRequest{ Name: secret.Name + "/versions/1", }) // Destroy it permanently _, err = client.DestroySecretVersion(ctx, &smpb.DestroySecretVersionRequest{ Name: secret.Name + "/versions/1", }) ``` -------------------------------- ### Run CI/CD with stub mode Source: https://localgcp.com/docs/vertex-ai.html Execute tests without an active Ollama instance by relying on deterministic stub responses from localgcp. ```bash # CI/CD: just start localgcp, no Ollama needed $ localgcp up & $ go test ./... # Vertex AI calls return stub responses ``` -------------------------------- ### Load Data Source: https://localgcp.com/docs/bigquery.html Load data files into tables using the CLI or SQL commands. ```bash $ localbq load mydata.users users.parquet ``` ```sql LOAD DATA INTO mydata.users FROM '/path/to/users.parquet' ``` -------------------------------- ### Generate Signed URL Source: https://localgcp.com/docs/cloud-storage.html Use the localgcp endpoint to generate a pre-signed download URL for an object. ```bash $ curl -X POST http://localhost:4443/_localgcp/sign \ -H "Content-Type: application/json" \ -d '{"bucket":"my-bucket","object":"hello.txt","ttl_seconds":3600}' ``` -------------------------------- ### Connect with Go Source: https://localgcp.com/docs/bigquery.html Configure the Go BigQuery client to use the local endpoint and disable authentication. ```go package main import ( "context" "fmt" "log" "cloud.google.com/go/bigquery" "google.golang.org/api/iterator" "google.golang.org/api/option" ) func main() { ctx := context.Background() client, err := bigquery.NewClient(ctx, "my-project", option.WithEndpoint("http://localhost:9060"), option.WithoutAuthentication(), ) if err != nil { log.Fatal(err) } defer client.Close() q := client.Query("SELECT 1 + 1 AS result") it, err := q.Read(ctx) if err != nil { log.Fatal(err) } for { var row []bigquery.Value err := it.Next(&row) if err == iterator.Done { break } if err != nil { log.Fatal(err) } fmt.Println(row) // [2] } } ``` -------------------------------- ### Configure Queue Retry Behavior Source: https://localgcp.com/docs/cloud-tasks.html Sets retry parameters including max attempts and backoff durations during queue creation. ```go queue, err := client.CreateQueue(ctx, &taskspb.CreateQueueRequest{ Parent: parent, Queue: &taskspb.Queue{ Name: parent + "/queues/retry-queue", RetryConfig: &taskspb.RetryConfig{ MaxAttempts: 5, MinBackoff: durationpb.New(1 * time.Second), MaxBackoff: durationpb.New(60 * time.Second), }, }, }) ``` -------------------------------- ### Standalone Mode Operations Source: https://localgcp.com/docs/bigquery.html Commands for running the localbq binary outside of the localgcp orchestration. ```bash $ docker run -p 9060:9060 ghcr.io/slokam-ai/localbq:latest ``` ```bash $ go install github.com/slokam-ai/localbq/cmd/localbq@latest ``` ```bash $ localbq up # start in foreground $ localbq up -d # start in background $ localbq stop # stop background server $ localbq status # check if running ``` -------------------------------- ### Configure Dead Letter Policy Source: https://localgcp.com/docs/pubsub.html Sets up a dead letter topic to receive messages after a specified number of failed delivery attempts. ```go // Create a dead letter topic dlTopic, _ := client.CreateTopic(ctx, "my-dead-letters") // Create subscription with dead letter policy sub, err := client.CreateSubscription(ctx, "my-sub", pubsub.SubscriptionConfig{ Topic: topic, DeadLetterPolicy: &pubsub.DeadLetterPolicy{ DeadLetterTopic: dlTopic.String(), MaxDeliveryAttempts: 5, }, }) ``` -------------------------------- ### Firestore Real-time Listeners Source: https://localgcp.com/docs/firestore.html Use Snapshots to listen for real-time updates on documents or collection queries. ```go // Listen for changes to a document snapIter := client.Collection("users").Doc("alice").Snapshots(ctx) defer snapIter.Stop() for { snap, err := snapIter.Next() if err != nil { break } fmt.Printf("Document changed: %v\n", snap.Data()) } // Listen for changes to a collection query queryIter := client.Collection("users"). Where("age", ">", 25). Snapshots(ctx) defer queryIter.Stop() for { snap, err := queryIter.Next() if err != nil { break } for _, change := range snap.Changes { fmt.Printf(" %s: %v\n", change.Doc.Ref.ID, change.Doc.Data()) } } ``` -------------------------------- ### Override Vertex AI model mappings Source: https://localgcp.com/docs/vertex-ai.html Use the --vertex-model-map flag to define custom mappings between Vertex AI model names and Ollama models. ```bash $ localgcp up --vertex-model-map="gemini-2.5-flash=mistral,gemini-2.5-pro=llama3.2:70b" ``` -------------------------------- ### Schedule Delayed Tasks Source: https://localgcp.com/docs/cloud-tasks.html Delays task execution by providing a future timestamp to the ScheduleTime field. ```go // Execute 5 minutes from now task, err := client.CreateTask(ctx, &taskspb.CreateTaskRequest{ Parent: queue.Name, Task: &taskspb.Task{ MessageType: &taskspb.Task_HttpRequest{ HttpRequest: &taskspb.HttpRequest{ Url: "http://localhost:9000/delayed-job", HttpMethod: taskspb.HttpMethod_POST, }, }, ScheduleTime: timestamppb.New(time.Now().Add(5 * time.Minute)), }, }) ``` -------------------------------- ### Firestore Transactions Source: https://localgcp.com/docs/firestore.html Perform atomic read-write operations using RunTransaction. ```go err = client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error { doc, err := tx.Get(client.Collection("accounts").Doc("alice")) if err != nil { return err } balance := doc.Data()["balance"].(int64) return tx.Set(client.Collection("accounts").Doc("alice"), map[string]interface{}{ "balance": balance + 100, }) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.