Create and deploy an HTTP Cloud Run function with Go

Introduction

This guide takes you through the process of writing a Cloud Run function using the Go runtime. There are two types of Cloud Run functions:

  • An HTTP function, which you invoke from standard HTTP requests.
  • An event-driven function, which is triggered by events in your Cloud infrastructure, such as messages on a Pub/Sub topic or changes in a Cloud Storage bucket.

For more detail, read writing HTTP functions and writing event-driven functions.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  8. Install and initialize the gcloud CLI.
  9. Update and install gcloud components with the following command.
    gcloud components update
  10. Prepare your development environment.

    Go to the Go setup guide

Create your function

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X

    mkdir ~/helloworld
    cd ~/helloworld
    

    Windows

    mkdir %HOMEPATH%\helloworld
    cd %HOMEPATH%\helloworld
    
  2. Create a file called hello_http.go in the helloworld directory with the following contents.

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"encoding/json"
    	"fmt"
    	"html"
    	"net/http"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    )
    
    func init() {
    	functions.HTTP("HelloHTTP", HelloHTTP)
    }
    
    // HelloHTTP is an HTTP Cloud Function with a request parameter.
    func HelloHTTP(w http.ResponseWriter, r *http.Request) {
    	var d struct {
    		Name string `json:"name"`
    	}
    	if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
    		fmt.Fprint(w, "Hello, World!")
    		return
    	}
    	if d.Name == "" {
    		fmt.Fprint(w, "Hello, World!")
    		return
    	}
    	fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
    }
    

    This example function takes a name supplied in the HTTP request and returns a greeting, or "Hello, World!" when no name is supplied.

Specify dependencies

Create a go.mod file to track your dependencies:

cd ~/helloworld
go mod init example.com/hello
go mod tidy

If your function has dependencies beyond the Functions Framework library, edit the go.mod file to add them. You can also specify dependencies with a Go vendor directory. For more details, read Specifying dependencies in Go.

Build and test your function locally

You can choose to build and test your function locally without deploying it. To do this, you must create a local main.go module to invoke your function.

  1. Create a cmd subdirectory:

    mkdir ~/helloworld/cmd
    cd ~/helloworld/cmd
    
  2. Create a main go module to invoke your function by copying the following code snippet into a file called main.go in the ~/helloworld/cmd directory:

    package main
    
    import (
      "log"
      "os"
    
      // Blank-import the function package so the init() runs
      _ "example.com/hello"
      "github.com/GoogleCloudPlatform/functions-framework-go/funcframework"
    )
    
    func main() {
      // Use PORT environment variable, or default to 8080.
      port := "8080"
      if envPort := os.Getenv("PORT"); envPort != "" {
        port = envPort
      }
      if err := funcframework.Start(port); err != nil {
        log.Fatalf("funcframework.Start: %v\n", err)
      }
    }
    
  3. Resolve your remaining dependencies with the go mod tidy command:

    go mod tidy
    
  4. Run your function locally with the following command:

    export FUNCTION_TARGET=HelloHTTP
    go run ~/helloworld/cmd/main.go
    
  5. Test your function by visiting http://localhost:8080 in a browser or by running curl localhost:8080 from another window.

    See Sending requests to local functions for more detail.

Deploy your function

To deploy your function, run the following command in the helloworld directory:

  gcloud functions deploy go-http-function \
    --gen2 \
    --runtime=go122 \
    --region=REGION \
    --source=. \
    --entry-point=HelloHTTP \
    --trigger-http \
    --allow-unauthenticated

Replace REGION with the name of the Google Cloud region where you want to deploy your function (for example, us-west1).

The optional --allow-unauthenticated flag lets you reach your function without authentication.

Test your deployed function

  1. After the function deploys, note the uri property from the output of the gcloud functions deploy command, or retrieve it with the following command:

      gcloud functions describe go-http-function \
        --region=REGION
    

    Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

  2. Visit this URL in your browser. The function returns a "Hello World!" message.

    You can also find this URL in Google Cloud console. Go to the Cloud Run functions Overview page, and click the name of your function to open its Function details page. Open the TRIGGER tab to see your function's URL.

View your function's logs

View the logs with the command-line tool

You can review your function's logs with the Cloud Logging UI or via the Google Cloud CLI.

To view logs for your function with the gcloud CLI, use the logs read command:

    gcloud functions logs read \
      --gen2 \
      --limit=10 \
      --region=REGION \
      go-http-function

Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

The output resembles the following:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.473
LOG:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.370
LOG:

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.280
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "h-hello_h_t_t_p-1" on port 8080.

LEVEL: I
NAME: hellohttp
TIME_UTC: 2023-05-31 21:52:20.108
LOG:

View logs with the logging dashboard

To view the logs for your function with the logging dashboard, open the Cloud Run functions Overview page and click the name of your function from the list, then click the Logs tab.