### Install Speech API Client Library for Go Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/captionasync/README.md Install the Speech API client library for Go using the go get command. This is a prerequisite for running the examples. ```bash go get -u cloud.google.com/go/speech/apiv1 ``` -------------------------------- ### Example Output of Go Bigtable Quickstart Source: https://github.com/googlecloudplatform/golang-samples/blob/main/bigtable/quickstart/README.md This is an example of the expected output when the Go quickstart successfully reads a row from Cloud Bigtable. ```text 2018/06/15 18:50:52 Getting a single row by row key: 2018/06/15 18:50:54 Row key: r1 2018/06/15 18:50:54 Data: test-value ``` -------------------------------- ### Install Speech API Client for Go Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/speech_quickstart_v2/README.md Install the Speech API client library for Go using the go get command before running the sample. ```bash go get -u cloud.google.com/go/speech/apiv2 ``` -------------------------------- ### Run Speech API Example with Local File Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/captionasync/README.md Execute the captionasync.go example with a local audio file. Ensure the path to the audio file is correctly provided. ```bash go run captionasync.go ../testdata/quit.raw ``` -------------------------------- ### Run Speech API Example with Local Audio File Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/caption/README.md Execute the caption.go example with a local audio file. Ensure the path to the audio file is correctly specified. ```bash go run caption.go ../testdata/audio.raw ``` -------------------------------- ### Install and Run Cloud SQL Proxy Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Commands to download, make executable, and start the Cloud SQL proxy for local development. Ensure you replace placeholders like [your project], [your region], and INSTANCE_NAME. ```bash curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.386 chmod +x cloud_sql_proxy ``` ```bash PROJECT_ID=[your project] REGION=[your region] CONNECTION_NAME=$PROJECT_ID:$REGION:$INSTANCE_NAME ./cloud_sql_proxy -instances="$CONNECTION_NAME"=tcp:3306 ``` -------------------------------- ### Run Go Quickstart to Read a Bigtable Row Source: https://github.com/googlecloudplatform/golang-samples/blob/main/bigtable/quickstart/README.md Execute the Go quickstart application to read the row previously set using `cbt`. Ensure you provide your project and instance IDs. ```bash `go run main.go -project PROJECT_ID -instance INSTANCE_ID -table my-table ``` -------------------------------- ### Build and Run Live Caption Example Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/livecaption_from_file/README.md Build the Go sample and run the livecaption_from_file executable with a path to an audio file to generate live captions. ```bash go build livecaption_from_file ../testdata/audio.raw ``` -------------------------------- ### Clone Example Code Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Retrieve the Go sample application code from the GitHub repository. ```bash git clone https://github.com/GoogleCloudPlatform/golang-samples.git cd go/src/github.com/GoogleCloudPlatform/golang-samples/getting-started/devflowapp ``` -------------------------------- ### Execute a sample program Source: https://github.com/googlecloudplatform/golang-samples/blob/main/profiler/README.md Start the sample program to collect profiling data. The program will display messages as profiles are uploaded to your GCP project. Press Ctrl-C to stop. ```bash go run main.go ``` -------------------------------- ### Run Go Backend Locally Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started/README.md Execute the main application file to start the Go backend locally. ```bash go run app.go ``` -------------------------------- ### Launch Cloud SQL Proxy with TCP (Linux/Mac) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/postgres/database-sql/README.md Start the Cloud SQL Auth proxy in the background using a TCP connection on Linux or Mac OS. Ensure you have downloaded and installed the proxy. ```bash ./cloud-sql-proxy :: --port=5432 & ``` -------------------------------- ### Navigate to hotapp sample directory Source: https://github.com/googlecloudplatform/golang-samples/blob/main/profiler/README.md Change to the source directory of the sample you want to execute. This example navigates to the 'hotapp' sample. ```bash cd ~/gopath/src/github.com/GoogleCloudPlatform/golang-samples/profiler/hotapp ``` -------------------------------- ### Install Go Libraries Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/googlecloudstorageclient/download.txt Install the required Go libraries for Google Cloud Storage and App Engine integration. Ensure your GOPATH is set correctly before running these commands. ```bash go get -u golang.org/x/oauth2 go get -u cloud.google.com/go/storage go get -u google.golang.org/appengine/... ``` -------------------------------- ### Run Speech API Example with GCS Audio File Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/caption/README.md Execute the caption.go example with an audio file stored in Google Cloud Storage. Replace 'gs://...' with the actual GCS path. ```bash go run caption.go gs://... ``` -------------------------------- ### Setting up and using GimmeProj in Integration Tests Source: https://github.com/googlecloudplatform/golang-samples/blob/main/testing/gimmeproj/README.md This example demonstrates how to download, make executable, and use gimmeproj within integration tests. It includes setting up a project lease and ensuring the project is returned to the pool upon test completion using a trap. ```bash set -e -x curl https://storage.googleapis.com/gimme-proj/linux_amd64/gimmeproj > gimmeproj chmod +x gimmeproj ./gimmeproj version export TEST_PROJECT=$(./gimmeproj -project meta-project lease 15m) trap "./gimmeproj -project meta-project done $TEST_PROJECT" EXIT go test .... ``` -------------------------------- ### Run the Spanner OpenTelemetry Tracing Example Source: https://github.com/googlecloudplatform/golang-samples/blob/main/spanner/opentelemetry/tracing/Readme.md Execute the Go application from the command line after setting up the configuration and environment variables. ```bash go run spanner_opentelemetry_tracing.go ``` -------------------------------- ### Run Speech API Example with GCS File Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/captionasync/README.md Execute the captionasync.go example with an audio file stored in Google Cloud Storage. Replace 'gs://...' with the actual GCS path. ```bash go run captionasync.go gs://... ``` -------------------------------- ### Run Live Caption Example with Local File Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/livecaption/README.md Build the live caption Go program and pipe the content of an audio file to it for transcription. Ensure the audio file is in a compatible format. ```bash go build cat ../testdata/audio.raw | livecaption ``` -------------------------------- ### Run the Shakespeare Application Server Source: https://github.com/googlecloudplatform/golang-samples/blob/main/profiler/shakesapp/README.md Execute this command to start the Go server for the Shakespeare application. ```sh go run . ``` -------------------------------- ### Start Local Ping Service Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-ping/README.md Start the ping service locally, listening on a specified port. This command should be run from the 'ping' subdirectory. ```sh cd ./ping PORT=9090 go run . ``` -------------------------------- ### Run Word Offset Example Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/wordoffset/README.md Execute the word offset Go sample with a local audio file. Ensure the audio file path is correctly provided. ```bash go run wordoffset.go ../testdata/audio.raw ``` -------------------------------- ### Create Bigtable Table, Column Family, and Set Data using cbt Source: https://github.com/googlecloudplatform/golang-samples/blob/main/bigtable/quickstart/README.md Use the `cbt` command-line tool to set up a Bigtable table, column family, and add initial data for the quickstart. ```bash cbt createtable my-table cbt createfamily my-table cf1 cbt set my-table r1 cf1:c1=test-value ``` -------------------------------- ### Start Cloud SQL Auth Proxy for TCP and Unix Socket Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Start two instances of the Cloud SQL Auth Proxy: one for TCP connection on port 3306 and another for Unix socket connection in the /cloudsql directory. ```bash cloud-sql-proxy :: --port=3306 cloud-sql-proxy :: \ --unix-socket=/cloudsql ``` -------------------------------- ### Start Local Relay Service Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-ping/README.md Start the relay service locally, configured to connect to the local ping service using insecure and unauthenticated connections. This is primarily for local development. ```sh cd ./relay GRPC_PING_INSECURE=1 GRPC_PING_HOST=localhost:9090 GRPC_PING_UNAUTHENTICATED=1 \ go run . ``` -------------------------------- ### Run gRPC Ping Server Locally Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-ping/README.md Start the gRPC ping server locally. This command should be run from the 'ping' subdirectory. ```sh cd ping go run . ``` -------------------------------- ### Retrieve Protoc Plugin for Go Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-ping/README.md Install or update the protoc plugin for Go. This is a prerequisite for regenerating Go code from protobuf definitions. ```sh go get -u github.com/golang/protobuf/protoc-gen-go ``` -------------------------------- ### gRPC Client Output Example Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-server-streaming/README.md Observe the output when the client successfully connects to the server and receives time messages. The client prints each message as it arrives. ```Shell rpc established to timeserver, starting to stream received message: current_timestamp: 2020-01-15T01:12:29Z received message: current_timestamp: 2020-01-15T01:12:30Z received message: current_timestamp: 2020-01-15T01:12:31Z received message: current_timestamp: 2020-01-15T01:12:32Z received message: current_timestamp: 2020-01-15T01:12:33Z end of stream ``` -------------------------------- ### Launch Cloud SQL Proxy with Unix Domain Socket Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/postgres/database-sql/README.md Start the Cloud SQL Auth proxy in the background using a Unix domain socket on Linux or Mac OS. Ensure the directory for the socket is created and accessible. ```bash ./cloud-sql-proxy --unix-socket=./cloudsql :: & ``` -------------------------------- ### Launch Cloud SQL Proxy with TCP (Linux/Mac) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Launch the Cloud SQL Auth proxy in the background using a TCP connection on Linux or Mac OS. Ensure you have the proxy installed and configured. ```bash ./cloud-sql-proxy :: --port=3306 & ``` -------------------------------- ### App Engine `backends.yaml` configuration Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/modules/converting.txt This is an example of a `backends.yaml` file used in App Engine. It defines different backend services with their configurations. ```yaml backends: - name: memdb class: B8 instances: 5 - name: worker start: _go_app options: failfast - name: cmdline options: dynamic ``` -------------------------------- ### Function Arguments for Go Samples Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md Minimize function arguments, typically including an io.Writer and project ID. If additional arguments are needed, provide an example value within the function body. ```go // delete deletes the resource identified by name. func delete(w io.Writer, name string) error { // name := "/projects/my-project/resources/my-resource" ctx := context.Background() client, err := foo.NewClient(ctx) if err != nil { return fmt.Errorf("foo.NewClient: %v", err) } if err := client.Delete(name); err != nil { return fmt.Errorf("Delete: %v", err) } return nil } ``` -------------------------------- ### Run gRPC Client Request Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-server-streaming/README.md Execute the Go client to connect to the deployed gRPC server and receive streamed time messages. Ensure Go 1.25 or higher is installed. ```Shell go run ./client -duration 5 -server :443 ``` -------------------------------- ### Filter by LastName and Height, Order by Height Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/datastore/indexes/queries.txt Example query filtering by LastName and Height, then ordering by Height in descending order. Ensure an index supports these filters and ordering. ```sql SELECT * FROM Person WHERE LastName = "Smith" AND Height < 72 ORDER BY Height DESC ``` -------------------------------- ### Filter by LastName, Order by FirstName and Height Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/datastore/indexes/queries.txt This example shows filtering by LastName and then ordering by two properties: FirstName and Height in ascending order. This requires a composite index. ```sql SELECT * FROM Person WHERE LastName = "Blair" ORDER BY FirstName, Height ASC ``` -------------------------------- ### Launch Cloud SQL Proxy with TCP (Windows) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/postgres/database-sql/README.md Start the Cloud SQL Auth proxy in a separate PowerShell session using a TCP connection on Windows. Specify the correct path to the proxy executable. ```powershell Start-Process -filepath "C:\" -ArgumentList ":: --port=5432" ``` -------------------------------- ### Build and Run Video Intelligence Go Sample Source: https://github.com/googlecloudplatform/golang-samples/blob/main/videointelligence/video_analyze/README.md Build the Go sample using 'go build' and then run the executable with a local file or a Cloud Storage URI as an argument. ```bash go build -o video_analyze gcloud storage cp gs://cloud-samples-data/video/cat.mp4 . ./video_analyze cat.mp4 ./video_analyze gs://cloud-samples-data/video/cat.mp4 ``` -------------------------------- ### Entity Analysis Output Example Source: https://github.com/googlecloudplatform/golang-samples/blob/main/language/analyze/README.md Example output from the Natural Language API entity analysis, showing detected entities, their types, salience, and mentions. ```text entities: < name: "Renee French" type: PERSON salience: 0.4693242 mentions: < text: < content: "Renee French" > > > entities: < name: "Go" type: ORGANIZATION metadata: < key: "wikipedia_url" value: "http://en.wikipedia.org/wiki/Go_(programming_language)" > salience: 0.34126133 mentions: < text: < content: "Go" begin_offset: 26 > > > language: "en" ``` -------------------------------- ### Run Instance Admin Sample Source: https://github.com/googlecloudplatform/golang-samples/blob/main/bigtable/instanceadmin/README.md Execute the Go sample application to create a Bigtable instance. Replace placeholders with your project ID, desired instance ID, and zone. ```bash go run main.go -project YOUR_PROJECT_ID -instance YOUR_INSTANCE_ID -zone YOUR_ZONE ``` -------------------------------- ### Set up GOPATH Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/googlecloudstorageclient/download.txt Configure your GOPATH environment variable. This is a prerequisite for Go development. ```bash mkdir -p $HOME/go export GOPATH=$HOME/go ``` -------------------------------- ### Clone the Shakespeare Application Repository Source: https://github.com/googlecloudplatform/golang-samples/blob/main/profiler/shakesapp/README.md Use this command to get the application code from GitHub. ```sh git clone https://github.com/GoogleCloudPlatform/golang-samples.git cd golang-samples/profiler/shakesapp ``` -------------------------------- ### Build and Run Natural Language Analysis Sample Source: https://github.com/googlecloudplatform/golang-samples/blob/main/language/analyze/README.md Build the Go sample and run it with a command (entities, sentiment, or syntax) and the text to analyze. ```bash go build && ./analyze ``` -------------------------------- ### Deploy Cloud Storage Hello World Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/helloworld/README.md Deploys a Go function that is triggered by changes in a Cloud Storage bucket. Ensure the BUCKET_NAME environment variable is set. ```bash export BUCKET_NAME=... ``` ```bash gcloud storage buckets create gs://$BUCKET_NAME ``` ```bash gcloud functions deploy HelloGCS --runtime=go113 --entry-point=HelloGCS --trigger-resource=$BUCKET_NAME --trigger-event=providers/cloud.storage/eventTypes/object.change ``` -------------------------------- ### Get GCE Instance IP Address Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Retrieve the external IP address of the GCE instance hosting the gRPC server. ```bash gcloud compute instances list --filter=grpc-host ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/googlecloudplatform/golang-samples/blob/main/dataflow/flex-templates/wordcount/README.md Clones the golang-samples repository and navigates to the Wordcount sample directory. ```sh git clone https://github.com/GoogleCloudPlatform/golang-samples.git cd golang-samples/dataflow/flex-templates/wordcount ``` -------------------------------- ### Build and Run Devflowapp in Docker Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Commands to build a Docker image for the devflowapp and run it as a detached container. The MESSAGE_SERVICE is set to 'mock' for this example. ```bash docker build -f Dockerfile -t devflowapp-image . docker run -itd --rm --name devflowapp \ -p 8080:8080 \ --env MESSAGE_SERVICE=mock \ devflowapp-image ``` -------------------------------- ### Set up Test Projects and Service Accounts Source: https://github.com/googlecloudplatform/golang-samples/blob/main/testing/kokoro/readme.md Use this script to automate the creation and configuration of multiple test projects and their associated service accounts. It assigns owner and KMS encrypter/decrypter roles to the service accounts for each test project, and also grants owner role to the main project for resource access. ```bash for i in {2..10}; do gcloud config set project golang-samples-tests-$i gcloud iam service-accounts create kokoro-golang-samples-tests-$i --display-name "Kokoro golang-samples-tests $i" gcloud iam service-accounts keys create kokoro-golang-samples-tests-$i.json --iam-account kokoro-golang-samples-tests-$i@golang-samples-tests-$i.iam.gserviceaccount.com gcloud projects add-iam-policy-binding golang-samples-tests-$i --member serviceAccount:kokoro-golang-samples-tests-$i@golang-samples-tests-$i.iam.gserviceaccount.com --role roles/owner gcloud projects add-iam-policy-binding golang-samples-tests-$i --member serviceAccount:kokoro-golang-samples-tests-$i@golang-samples-tests-$i.iam.gserviceaccount.com --role roles/cloudkms.cryptoKeyEncrypterDecrypter # Every service account should have access to the main project ( # for resources like Spanner). gcloud projects add-iam-policy-binding golang-samples-tests --member serviceAccount:kokoro-golang-samples-tests-$i@golang-samples-tests-$i.iam.gserviceaccount.com --role roles/owner done ``` -------------------------------- ### Run Vision API Detection Sample Source: https://github.com/googlecloudplatform/golang-samples/blob/main/vision/detect/README.md Build and run the Vision API detection sample with different input sources: local file, Google Cloud Storage URI, or a public URL. ```bash go run detect.go main.go ../testdata/cat.jpg ``` ```bash go run detect.go main.go gs://... ``` ```bash go run detect.go main.go https://... ``` -------------------------------- ### Run hotapp sample with specific options Source: https://github.com/googlecloudplatform/golang-samples/blob/main/profiler/README.md Run the 'hotapp' service with these command-line options to generate profile data consistent with the Profiler documentation. ```bash go run main.go -service=docdemo-service -local_work -skew=75 -version=1.75.0 ``` -------------------------------- ### Test Inspect String Functionality in Go Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md This test verifies the inspectString function by writing to a buffer and checking for expected output. It uses SystemTest for environment setup. ```go func TestInspectString(t *testing.T) { tc := testutil.SystemTest(t) buf := new(bytes.Buffer) err := inspectString(buf, tc.ProjectID, "I'm Gary and my email is gary@example.com") if err != nil { t.Errorf("TestInspectFile: %v", err) } got := buf.String() if want := "Info type: EMAIL_ADDRESS"; !strings.Contains(got, want) { t.Errorf("got %q, want %q", got, want) } } ``` -------------------------------- ### Deploy Pub/Sub Hello World Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/helloworld/README.md Deploys a Go function that is triggered by messages published to a Pub/Sub topic. Ensure the FUNCTIONS_TOPIC environment variable is set. ```bash export FUNCTIONS_TOPIC=example-topic ``` ```bash gcloud functions deploy HelloPubSub --runtime=go113 --trigger-topic=$FUNCTIONS_TOPIC ``` -------------------------------- ### Run Live Caption with Specific Audio Source Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/livecaption/README.md Adapt the gst-launch-1.0 command to use a specific audio source device (e.g., 'osxaudiosrc device=39') for capturing microphone audio for live captioning. ```bash gst-launch-1.0 -v osxaudiosrc device=39 ! audioconvert ! audioresample ! audio/x-raw,channels=1,rate=16000 ! filesink location=/dev/stdout | livecaption ``` -------------------------------- ### Run Locally with Mock Service Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Execute the application locally using a mock message service for development and testing. Ensure Go dependencies are fetched. ```bash export MESSAGE_SERVICE=mock go get -d -v ./... go run devflowapp.go ``` -------------------------------- ### Running Linting and Vet Tools Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md Execute the 'make lint' command from the repository root to format code with gofmt and check for common errors with go vet. Specify the directory to lint if needed. ```bash make lint dir=iam ``` -------------------------------- ### Submit Build with Cloud Build Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Build and execute unit tests using Cloud Build by submitting the configuration file. ```bash gcloud builds submit --config build/cb-unittest.yaml . ``` -------------------------------- ### Launch Cloud SQL Proxy (Linux/Mac) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/sqlserver/database-sql/README.md Launch the Cloud SQL Auth Proxy in the background using a TCP connection on Linux or macOS. ```bash ./cloud-sql-proxy :: --port=1433 & ``` -------------------------------- ### Address Specific Backends and Instances in Go Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/backends/index.txt Use `appengine.BackendInstance` to get the name and index of the current backend, and `appengine.BackendHostname` to construct its specific hostname. This is useful for inter-backend communication or specific routing. ```go func handler(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) // Get the details of the current backend. name, index := appengine.BackendInstance(ctx) // Get the hostname of this specific backend. hostname := appengine.BackendHostname(ctx, name, index) fmt.Fprint(w, "I am backend %s instance %d ", name, index) fmt.Fprint(w, "serving http://%s", hostname) ``` -------------------------------- ### Navigating to Repository Directory Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md Change your current directory to the cloned repository's root folder to begin making changes. ```bash cd golang-samples ``` -------------------------------- ### Deploy Service to Cloud Run with Environment Variables Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Deploy the service to Cloud Run, configuring Cloud SQL instances and environment variables for database connection. It's recommended to use Secret Manager for sensitive data. ```bash gcloud run deploy run-sql --image gcr.io/[YOUR_PROJECT_ID]/run-sql \ --add-cloudsql-instances '::' \ --update-env-vars INSTANCE_UNIX_SOCKET='/cloudsql/::' \ --update-env-vars DB_USER='' \ --update-env-vars DB_PASS='' \ --update-env-vars DB_NAME='' ``` -------------------------------- ### Run gRPC Ping Client Locally (Relayed Server) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-ping/README.md Send a relayed ping request to a locally running gRPC server setup. This command should be run from the root directory of the grpc-ping project. ```sh go run ./client -server localhost:8080 -insecure -relay -message "Hello Relayed Friend!" ``` -------------------------------- ### Connect to Cloud SQL Instance Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Establish a connection to the Cloud SQL instance using the gcloud command-line tool. ```bash INSTANCE_NAME=devflowapp gcloud sql connect $INSTANCE_NAME --user=root ``` -------------------------------- ### GimmeProj Usage and Commands Source: https://github.com/googlecloudplatform/golang-samples/blob/main/testing/gimmeproj/README.md This section outlines the command-line interface for gimmeproj, including its primary usage pattern and available commands for project leasing and pool management. ```bash Usage: gimmeproj -project=[meta project ID] command Commands: lease [duration] Leases a project for a given duration. Prints the project ID to stdout. done [project ID] Returns a project to the pool. Administrative commands: pool-add [project ID] Adds a project to the pool. pool-rm [project ID] Removes a project from the pool. status Displays the current status of the meta project. ``` -------------------------------- ### Filter by LastName and Height, Order by Height (Different Value) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/datastore/indexes/queries.txt Similar to the previous example, this query filters by LastName and Height with a different height threshold, ordering by Height descending. This demonstrates variations in filtering criteria. ```sql SELECT * FROM Person WHERE LastName = "Jones" AND Height < 63 ORDER BY Height DESC ``` -------------------------------- ### Create GCE Instance for gRPC Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Create a Google Compute Engine instance and SSH into it to host the gRPC service. ```bash gcloud compute instances create grpc-host --image-family cos-stable --image-project cos-cloud --tags=http-server gcloud compute ssh grpc-host ``` -------------------------------- ### Deploy HTTP Hello World Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/helloworld/README.md Deploys a Go function that is triggered by HTTP requests. The function is deployed to the us-central1 region. ```bash gcloud functions deploy HelloHTTP --region=us-central1 --runtime=go113 --trigger-http ``` ```bash export BASE_URL=https://REGION-PROJECT.cloudfunctions.net/ ``` -------------------------------- ### Basic Go Runtime Configuration Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/modules/index.txt A minimal configuration for a Go runtime service in App Engine. ```yaml runtime: go api_version: go1 ``` -------------------------------- ### List Monitored Resources and Metric Descriptors Source: https://github.com/googlecloudplatform/golang-samples/blob/main/monitoring/README.md Use this command to list Google Cloud Monitoring v3 environment details. Ensure you have set up your local development environment and have authenticated with Google Cloud. ```bash go get -u github.com/GoogleCloudPlatform/golang-samples/monitoring/... cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/monitoring go run listresources/*.go ``` -------------------------------- ### Test Pub/Sub Hello World Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/helloworld/README.md Runs the system tests for the HelloPubSub function. This verifies the Pub/Sub trigger. ```bash go test -v ./hello_pubsub_system_test.go ``` -------------------------------- ### Run Dataflow Flex Template Source: https://github.com/googlecloudplatform/golang-samples/blob/main/dataflow/flex-templates/wordcount/README.md Use this command to launch a Dataflow Flex Template. Ensure the `TEMPLATE_PATH` variable is set, and provide input and output parameters as needed. The input parameter is optional and defaults to a public bucket. ```bash export REGION="us-central1" # Run the Flex Template. gcloud dataflow flex-template run "wordcount-`date +%Y%m%d-%H%M%S`" \ --template-file-gcs-location "$TEMPLATE_PATH" \ --parameters input="projects/$PROJECT/subscriptions/$SUBSCRIPTION" \ --parameters output="gs://$BUCKET/counts.txt" \ --region "$REGION" ``` -------------------------------- ### Test Cloud Storage Hello World Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/helloworld/README.md Runs the system tests for the HelloGCS function. This verifies the deployment and trigger. ```bash go test -v ./hello_cloud_storage_system_test.go ``` -------------------------------- ### Test HTTP Hello World Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/helloworld/README.md Runs the system tests for the HelloHTTP function. This verifies the HTTP trigger and response. ```bash go test -v ./hello_http_system_test.go ``` -------------------------------- ### Run Security System Tests Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/security/README.md Executes Go system tests for security. Ensure you have set up credentials and the base URL. ```bash go test -v ./security_system_test.go ``` -------------------------------- ### Run gRPC Client with API Key Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Run the gRPC client from your local machine, authenticating with an API key and specifying the server address. ```bash go run client/main.go --api-key=AIza.... --addr=YOUR_SERVER_IP_ADDRESS:80 [message] ``` -------------------------------- ### Capture Audio from Mic using gst-launch-1.0 Source: https://github.com/googlecloudplatform/golang-samples/blob/main/speech/livecaption/README.md Use gst-launch-1.0 to capture audio from the microphone, convert it to a compatible format (1 channel, 16000 Hz), and pipe it to the livecaption program for real-time transcription. ```bash gst-launch-1.0 -v pulsesrc ! audioconvert ! audioresample ! audio/x-raw,channels=1,rate=16000 ! filesink location=/dev/stdout | livecaption ``` -------------------------------- ### Initialize Environment Variables for Cloud SQL Proxy (TCP) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/postgres/database-sql/README.md Set environment variables for database connection details when using the Cloud SQL Auth proxy with a TCP connection on Linux or Mac OS. ```bash export INSTANCE_HOST='127.0.0.1' export DB_PORT='5432' export DB_USER='' export DB_PASS='' export DB_NAME='' ``` -------------------------------- ### Run gRPC Server Locally Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Execute the gRPC server locally using `go run`. This is useful for initial testing and development. ```bash go run server/main.go ``` -------------------------------- ### Forking a Repository with GitHub CLI Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md Use this command to fork the golang-samples repository using the GitHub CLI. Replace 'GoogleCloudPlatform/golang-samples' with the repository you wish to fork. ```bash gh repo fork GoogleCloudPlatform/golang-samples ``` -------------------------------- ### Deploy App Engine Application Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/background/README.md Use this command to deploy your App Engine application. Ensure GO111MODULE is set to 'on'. ```bash GO111MODULE=on gcloud app deploy ``` -------------------------------- ### Create and Write Custom Metric Source: https://github.com/googlecloudplatform/golang-samples/blob/main/monitoring/README.md This command demonstrates creating a custom metric, writing a time series value to it, and reading it back. Ensure your project ID is correctly specified. ```bash go run custommetric/*.go ``` -------------------------------- ### Deploy Go Backend to App Engine Flex Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started/README.md Deploy the Go backend to App Engine Flex after configuring the service name in app.yaml. ```bash gcloud app deploy ``` -------------------------------- ### Set Environment Variables for Cloud SQL Proxy (Linux/Mac) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Use these terminal commands to initialize environment variables for connecting to Cloud SQL via the proxy using a TCP connection on Linux or Mac OS. ```bash export INSTANCE_HOST='127.0.0.1' export DB_PORT='3306' export DB_USER='' export DB_PASS='' export DB_NAME='' ``` -------------------------------- ### Cloud Run `app.yaml` for cmdline service Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/modules/converting.txt This `app.yaml` configuration sets up the 'cmdline' service for Cloud Run using basic scaling with a maximum of 1 instance. ```yaml service: cmdline basic_scaling: max_instances: 1 ``` -------------------------------- ### Run Unit Tests Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Execute unit tests for the main and services packages of the application. ```bash go test go test -v github.com/GoogleCloudPlatform/golang-samples/getting-started/devflowapp/services ``` -------------------------------- ### Deploy Service to Cloud Run with Cloud SQL Instance Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/postgres/database-sql/README.md Deploy the containerized application to Cloud Run, specifying the Cloud SQL instance and environment variables for database connection. ```bash gcloud run deploy run-sql --image gcr.io/[YOUR_PROJECT_ID]/run-sql \ --add-cloudsql-instances '::' \ --set-env-vars INSTANCE_UNIX_SOCKET='/cloudsql/::' \ --set-env-vars DB_USER='' \ --set-env-vars DB_PASS='' \ --set-env-vars DB_NAME='' ``` -------------------------------- ### App Engine Manual Scaling with Single Instance Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/modules/index.txt Configure manual scaling for a service with a single instance. ```yaml service: my_service runtime: go api_version: go1 instance_class: B8 manual_scaling: instances: 1 ``` -------------------------------- ### Create GCE Instance with Cloud Platform Scopes Source: https://github.com/googlecloudplatform/golang-samples/blob/main/monitoring/README.md When creating a Google Compute Engine instance, specify these scopes to ensure automatic credential discovery for Google Cloud services. ```bash gcloud compute instances create --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/compute.readonly" test-instance ``` -------------------------------- ### Generate gRPC Descriptor Set Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Generate the `out.pb` file from the proto definition, which is required for deploying the service configuration. ```bash protoc \ --include_imports \ --include_source_info \ --descriptor_set_out out.pb \ helloworld/helloworld.proto ``` -------------------------------- ### Launch Cloud SQL Proxy with Unix Domain Socket Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Launch the Cloud SQL Auth proxy in the background using a Unix Domain Socket connection on Linux or Mac OS. Ensure the directory for the socket is created and accessible. ```bash ./cloud-sql-proxy --unix-socket=./cloudsql \ :: & ``` -------------------------------- ### Generate Protobuf Go Files Source: https://github.com/googlecloudplatform/golang-samples/blob/main/spanner/spanner_snippets/spanner/testdata/protos/README.md Use the protoc compiler to generate Go protobuf files from a .proto definition. Ensure you are in the correct directory before running. ```shell cd spanner_snippets/spanner/testdata protoc --proto_path=./protos/ --include_imports --descriptor_set_out=./protos/descriptors.pb --go_out=./protos/ protos/singer.proto ``` -------------------------------- ### Send Echo Request with API Key Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started/README.md Use the Go client to send a message to the backend, authenticated with an API key. Ensure you have created a project API key. ```bash go run client/main.go -api-key=AIza.... -host=https://my-app.appspot.com -echo message ``` -------------------------------- ### Set Environment Variables for Cloud SQL Proxy (Unix Domain Socket) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Use these terminal commands to initialize environment variables for connecting to Cloud SQL via the proxy using a Unix Domain Socket on Linux or Mac OS. ```bash export INSTANCE_UNIX_SOCKET='./cloudsql/::' export DB_USER='' export DB_PASS='' export DB_NAME='' ``` -------------------------------- ### Deploy HTTP Function Source: https://github.com/googlecloudplatform/golang-samples/blob/main/functions/security/README.md Deploys an HTTP-triggered Go function. Ensure the source path is correct. ```bash gcloud alpha functions deploy HelloHTTP --region=us-central1 --runtime=go111 --trigger-http --source=../helloworld ``` -------------------------------- ### Run Devflowapp Locally with Database Connection Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Set environment variables for database credentials and run the devflowapp. Ensure the Cloud SQL proxy is running in a separate terminal. ```bash DBPASSWORD=[your password] DBUSER=proxyuser DBHOST=127.0.0.1 DATABASE=messagesdb export MYSQL_CONNECTION="$DBUSER:$DBPASSWORD@tcp($DBHOST:3306)/$DATABASE" go run devflowapp.go ``` -------------------------------- ### Deploy Application to App Engine Standard Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Deploy the Go application to App Engine Standard using the gcloud command-line tool, specifying the configuration file. ```bash gcloud app deploy cmd/app/app.standard.yaml ``` -------------------------------- ### Set Environment Variables for Cloud SQL Proxy (Linux/Mac) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/sqlserver/database-sql/README.md Set these environment variables before launching the Cloud SQL Auth Proxy for a TCP connection on Linux or macOS. ```bash export INSTANCE_HOST='127.0.0.1' export DB_PORT='1433' export DB_USER='' export DB_PASS='' export DB_NAME='' ``` -------------------------------- ### Build and Push Docker Image with Specific Go Version Source: https://github.com/googlecloudplatform/golang-samples/blob/main/testing/docker/README.md Use this command to build a Docker image for a specific Go version (e.g., 1.25) and push it to the specified GCR repository. The `_GO_VERSION` and `_IMAGE_NAME` substitutions control the Go version and image name, respectively. ```bash gcloud builds submit . \ --project=golang-samples-tests \ --substitutions "_GO_VERSION=1.25,_IMAGE_NAME=go125" ``` -------------------------------- ### Import Cloud Run CI Package Source: https://github.com/googlecloudplatform/golang-samples/blob/main/internal/cloudrunci/README.md Import the necessary package for using the Cloud Run CI utility in your Go project. ```go import "github.com/GoogleCloudPlatform/golang-samples/internal/cloudrunci" ``` -------------------------------- ### Run System Tests Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md Execute system tests for a specific directory. Ensure you have a Google Cloud project and valid authentication set up. ```bash gcloud auth login --update-adc ``` ```bash export GOLANG_SAMPLES_PROJECT_ID= ``` ```bash make test dir=relative/dir ``` -------------------------------- ### Create Cloud SQL Instance Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Provision a Second Generation Cloud SQL instance named 'devflowapp' with specified machine type and region. ```bash INSTANCE_NAME=devflowapp MACHINE_TYPE=db-n1-standard-1 REGION=us-central1 gcloud sql instances create $INSTANCE_NAME --tier=$MACHINE_TYPE \ --region=$REGION ``` -------------------------------- ### Submit Docker Image Build with Cloud Build Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Submits a Docker image build to Cloud Build using a specified configuration file. ```bash gcloud builds submit --config build/cb-docker.yaml . ``` -------------------------------- ### Analyze Entities in Text with Go Sample Source: https://github.com/googlecloudplatform/golang-samples/blob/main/language/analyze/README.md Execute the Go sample to perform entity analysis on a given text string. This command demonstrates analyzing the text 'Renee French designed the Go gopher.' ```bash go build && ./analyze entities "Renee French designed the Go gopher." ``` -------------------------------- ### Describe Cloud SQL Instance Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Retrieve connection details, including connection name and IP address, for the specified Cloud SQL instance. ```bash INSTANCE_NAME=devflowapp gcloud sql instances describe $INSTANCE_NAME ``` -------------------------------- ### Create Cloud Storage Bucket Source: https://github.com/googlecloudplatform/golang-samples/blob/main/dataflow/flex-templates/wordcount/README.md Creates a Google Cloud Storage bucket. Replace 'your-gcs-bucket' with your desired bucket name. ```sh export BUCKET="your-gcs-bucket" gcloud storage buckets create gs://$BUCKET ``` -------------------------------- ### Run Integration Tests with Cloud SQL Auth Proxy Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/mysql/database-sql/README.md Configure environment variables for integration tests, including database credentials and connection details for both TCP and Unix socket connections via the Cloud SQL Auth Proxy. ```bash GOLANG_SAMPLES_E2E_TEST="yes" \ MYSQL_USER=some-user \ MYSQL_PASSWORD=some-pass MYSQL_DATABASE=some-db \ MYSQL_PORT=3307 \ MYSQL_HOST=127.0.0.1 MYSQL_UNIX_SOCKET='/cloudsql/::' MYSQL_INSTANCE='::' \ go test -v ``` -------------------------------- ### Enable OpenTelemetry Tracing Environment Variable Source: https://github.com/googlecloudplatform/golang-samples/blob/main/spanner/opentelemetry/tracing/Readme.md Set this environment variable to 'opentelemetry' to enable OpenTelemetry tracing for Google Cloud Go client libraries. ```bash export GOOGLE_API_GO_EXPERIMENTAL_TELEMETRY_PLATFORM_TRACING="opentelemetry" ``` -------------------------------- ### Send Request with JWT Authentication Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started/README.md Use the Go client to send a request to the backend, authenticated using a Service Account JSON key file. Download the key file before running. ```bash go run client/main.go -host=https://my-app.appspot.com -service-account=path_to_service_account.json ``` -------------------------------- ### Deploy Devflowapp to App Engine Flexible (Mocked DB) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Deploys the devflowapp to App Engine Flexible using a specific configuration file that mocks the database dependency. ```bash gcloud app deploy app-mock.yaml ``` -------------------------------- ### Send a Message Locally Source: https://github.com/googlecloudplatform/golang-samples/blob/main/getting-started/devflowapp/README.md Send a test message to a friend using the local development server. ```bash curl "http://localhost:8080/send?user=Friend1&friend=Friend2&text=We+miss+you!" ``` -------------------------------- ### Create Docker Network on GCE Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Create a bridge network for containers on the GCE instance to communicate. ```bash docker network create --driver bridge esp_net ``` -------------------------------- ### Initialize Environment Variables for Cloud SQL Proxy (TCP - Windows) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/postgres/database-sql/README.md Set environment variables for database connection details when using the Cloud SQL Auth proxy with a TCP connection on Windows PowerShell. ```powershell $env:INSTANCE_HOST="127.0.0.1" $env:DB_PORT="5432" $env:DB_USER="" $env:DB_PASS="" $env:DB_NAME="" ``` -------------------------------- ### Run Lint and Tests Source: https://github.com/googlecloudplatform/golang-samples/blob/main/CONTRIBUTING.md Before creating a Pull Request, ensure your code adheres to style guidelines and passes all tests by running `make lint test`. ```bash make lint test dir=relative/dir ``` -------------------------------- ### Set Environment Variables on GCE Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Set necessary environment variables on the GCE instance, including project ID and service name. ```bash GOOGLE_CLOUD_PROJECT=$(curl -s "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google") SERVICE_NAME=hellogrpc.endpoints.${GOOGLE_CLOUD_PROJECT}.cloud.goog ``` -------------------------------- ### Deploy Service Config with Auth Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Update the service configuration in Endpoints to include authentication settings using `api_config_auth.yaml`. ```bash gcloud endpoints services deploy out.pb api_config_auth.yaml ``` -------------------------------- ### Configure Docker for GCR on GCE Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Configure Docker to authenticate with Google Container Registry (GCR) on the GCE instance. ```bash docker-credential-gcr configure-docker ``` -------------------------------- ### Build Docker Image Locally Source: https://github.com/googlecloudplatform/golang-samples/blob/main/run/grpc-ping/README.md Build the Docker image for the gRPC ping application locally. This command should be run from the root directory of the project. ```sh docker build -t grpc-ping . ``` -------------------------------- ### Launch Cloud SQL Proxy (Windows/PowerShell) Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/sqlserver/database-sql/README.md Launch the Cloud SQL Auth Proxy in a separate PowerShell session using a TCP connection on Windows. ```powershell Start-Process -filepath "C:\" -ArgumentList ":: --port=1433" ``` -------------------------------- ### Deploy to GKE using kubectl Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Apply Kubernetes deployment and service configurations to deploy the gRPC server on GKE. ```bash kubectl apply -f deployment.yaml ``` -------------------------------- ### Deploy to Cloud Functions Source: https://github.com/googlecloudplatform/golang-samples/blob/main/cloudsql/sqlserver/database-sql/README.md Command to deploy a Go application to Cloud Functions (Gen 2), setting environment variables for Cloud SQL connection. Note the output URL for accessing the function. ```bash gcloud functions deploy votes --gen2 --runtime go120 --trigger-http \ --allow-unauthenticated \ --entry-point Votes \ --region \ --set-env-vars INSTANCE_CONNECTION_NAME=:: \ --set-env-vars DB_USER=$DB_USER \ --set-env-vars DB_PASS=$DB_PASS \ --set-env-vars DB_NAME=$DB_NAME ``` -------------------------------- ### Handle Backend Shutdown Requests in Go Source: https://github.com/googlecloudplatform/golang-samples/blob/main/docs/appengine/backends/index.txt Register a handler for the \/_ah/stop URL to gracefully shut down your backend. Ensure you implement `doSomeWork` and `saveState` to perform necessary cleanup operations. ```go func init() { http.HandleFunc("/_ah/stop", shutdownHandler) } func shutdownHandler(w http.ResponseWriter, r *http.Request) { doSomeWork() saveState() } ``` -------------------------------- ### Run gRPC Client with Service Account Key Source: https://github.com/googlecloudplatform/golang-samples/blob/main/endpoints/getting-started-grpc/README.md Authenticate gRPC client requests using a service account key and specifying the audience and server address. ```bash go run client/main.go \ --keyfile=SERVICE_ACCOUNT_KEY.json \ --audience=hellogrpc.endpoints.PROJECT_ID.cloud.goog \ --addr=YOUR_SERVER_IP_ADDRESS:80 \ [message] ```