The Go Runtime

The Cloud Functions Go runtime is based on Go version 1.11.6. For instructions on how to prepare your local machine for Go development, see Setting Up a Go Development Environment.

To get started with Go on Cloud Functions, see the Quickstart.

Selecting the runtime

You can select the Go runtime for your function during deployment.

gcloud

If you are using the gcloud command-line tool, you can specify the runtime by using the --runtime parameter. For example:

gcloud functions deploy FUNCTION_NAME --runtime go111 FLAGS...

FLAGS... refers to arguments passed during the first deployment of your function. For more information regarding required and optional arguments, see Deploy using the gcloud tool.

Console

If you are using the GCP Console, you can select the runtime when you create and deploy a function.

  1. In the GCP Console, go to the Cloud Functions Overview page.

    Go to the Cloud Functions Overview page

    Make sure that the project for which you enabled Cloud Functions is selected.

  2. Click Create Function.

  3. Under Runtime, select Go 1.11.

Execution environment

The execution environment includes the runtime, the operating system, packages, and a library that invokes your function.

The Go runtime uses an execution environment based on Ubuntu 18.04 with Go version 1.11.6. See Cloud Functions Execution Environment for more information.

Source code structure

In order for Cloud Functions to find your function's definition, each runtime has certain structuring requirements for your source code. See Writing Cloud Functions for more information.

Specifying dependencies

Cloud Functions in Go must provide all of their dependencies via either Go modules with a go.mod file, or a vendor directory. For more information, see Specifying dependencies in Go.

One-time initialization

Your functions might need to do one-time initialization, like creating API clients and configuring database access. There are multiple ways to do this:

  • Use a func init() function to initialize values when a new instance of your function starts up. Note that code in the func init() function runs before your function receives its first request.

  • Use the sync.Once.Do() function to run code once per Cloud Functions instance. This is useful in cases where you only want to initialize on-demand rather than when your function instance first starts up. You might, for example, only need to initialize a database client under certain circumstances.

context.Context

Go's context package defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

API clients that outlive a given function invocation should be initialized with a global context.Context value, such as one created by the context.Background() function. To optimize performance, you might initialize a client in global scope. This client, and its context, might persist throughout the lifetime of a given function instance.

You should only use the function invocation context for objects or operations that fall within the lifetime of a specific function invocation. The invocation context might be canceled at any point after your function finishes executing, meaning any clients initialized using this context might be closed. The function invocation context is accessible through the function's arguments: usually r.Context() for HTTP functions, and ctx for background functions.

See the following code for an example using a Cloud Pub/Sub client:


// Package contexttip is an example of how to use Pub/Sub and context.Context in
// a Cloud Function.
package contexttip

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"

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

// projectID is set from the GCP_PROJECT environment variable, which is
// automatically set by the Cloud Functions runtime.
var projectID = os.Getenv("GCP_PROJECT")

// client is a global Pub/Sub client, initialized once per instance.
var client *pubsub.Client

func init() {
	// err is pre-declared to avoid shadowing client.
	var err error

	// client is initialized with context.Background() because it should
	// persist between function invocations.
	client, err = pubsub.NewClient(context.Background(), projectID)
	if err != nil {
		log.Fatalf("pubsub.NewClient: %v", err)
	}
}

type publishRequest struct {
	Topic string `json:"topic"`
}

// PublishMessage publishes a message to Pub/Sub. PublishMessage only works
// with topics that already exist.
func PublishMessage(w http.ResponseWriter, r *http.Request) {
	// Read the request body.
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("ioutil.ReadAll: %v", err)
		http.Error(w, "Error reading request", http.StatusBadRequest)
		return
	}

	// Parse the request body to get the topic name.
	p := publishRequest{}
	if err := json.Unmarshal(data, &p); err != nil {
		log.Printf("json.Unmarshal: %v", err)
		http.Error(w, "Error parsing request", http.StatusBadRequest)
		return
	}

	m := &pubsub.Message{
		Data: []byte("Test message"),
	}
	// Publish and Get use r.Context() because they are only needed for this
	// function invocation. If this were a background function, they would use
	// the ctx passed as an argument.
	id, err := client.Topic(p.Topic).Publish(r.Context(), m).Get(r.Context())
	if err != nil {
		log.Printf("topic(%s).Publish.Get: %v", p.Topic, err)
		http.Error(w, "Error publishing message", http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "Published msg: %v", id)
}
Was deze pagina nuttig? Laat ons weten hoe goed we u hebben geholpen:

Feedback verzenden over...

Cloud Functions Documentation