Go 執行階段

總覽

Cloud Run 函式的執行環境包含作業系統版本、附加套件、語言支援,以及支援和叫用函式的 Functions Framework 程式庫。這個環境由語言版本識別,稱為執行階段。

如要瞭解執行階段,以及各 Go 執行階段使用的 Ubuntu 版本,請參閱「Cloud Run 函式執行環境」。

選取執行階段

Cloud Run functions 支援多個 Go 版本,列載於「執行階段支援」頁面。部署期間,您可以為函式選取偏好的 Go 執行階段。

如果您使用 Google Cloud CLI,請透過 --runtime 參數指定執行階段,並搭配所選 Go 執行階段。例如:

gcloud functions deploy FUNCTION_NAME --no-gen2 --runtime go121 FLAGS...

FLAGS... 是在第一次部署函式期間傳遞的引數。如要進一步瞭解必要引數和選用引數,請參閱「部署 Cloud Run 函式」。

函式準備

您可以先在本機電腦編寫函式,再將其上傳。如要準備本機電腦,用於 Go 開發作業,請參閱「設定 Go 開發環境」。

如要快速在 Cloud Run functions 開始使用 Go,請參閱快速入門導覽課程

原始碼結構

原始碼必須遵循特定結構,Cloud Run functions 才能找到函式的定義。詳情請參閱「編寫 Cloud Run 函式」。

指定依附元件

以 Go 編寫的 Cloud Run 函式必須透過含有 go.mod 檔案或 vendor 目錄的 Go 模組,提供所有依附元件。詳情請參閱「以 Go 指定依附元件」。

環境變數

Go 執行階段會自動為函式設定特定環境變數,供函式視需要使用。詳情請參閱「使用環境變數」。

Context 類型

Go 的 context 套件定義了 Context 類型,可跨越 API 邊界,並在程序之間傳遞期限、取消信號和其他要求範圍的值。

下列 Cloud Run 函式程式碼範例,說明如何透過 Pub/Sub 用戶端存取背景資訊:


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
)

func init() {
	functions.CloudEvent("HelloPubSub", helloPubSub)
}

// MessagePublishedData contains the full Pub/Sub message
// See the documentation for more details:
// https://cloud.google.com/eventarc/docs/cloudevents#pubsub
type MessagePublishedData struct {
	Message PubSubMessage
}

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
type PubSubMessage struct {
	Data []byte `json:"data"`
}

// helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.
func helloPubSub(ctx context.Context, e event.Event) error {
	var msg MessagePublishedData
	if err := e.DataAs(&msg); err != nil {
		return fmt.Errorf("event.DataAs: %w", err)
	}

	name := string(msg.Message.Data) // Automatically decoded from base64.
	if name == "" {
		name = "World"
	}
	log.Printf("Hello, %s!", name)
	return nil
}