Go 執行階段

總覽

Cloud Run 函式會在環境中執行,該環境包含作業系統版本、外掛程式套件、語言支援,以及支援及叫用函式的 Functions Framework 程式庫。這個環境會透過語言版本識別,稱為執行階段。

如需一般執行階段的相關資訊,以及每個 Go 執行階段使用的 Ubuntu 版本,請參閱 Cloud Run 函式執行環境

選取執行階段

Cloud Run 函式支援多個 Go 版本,請參閱「執行階段支援」頁面。您可以在部署期間,針對函式選取偏好的 Go 執行階段。

gcloud

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

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

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

控制台

如果您使用的是 Google Cloud 控制台,請參閱 Google Cloud 控制台快速入門,瞭解詳細操作說明。

函式準備

您可以直接從 Google Cloud 控制台準備函式,也可以在本機上編寫函式並上傳。如要為 Go 開發作業準備本機電腦,請參閱「設定 Go 開發環境」。

如要快速開始在 Cloud Run 中使用 Go,請參閱快速入門

原始碼結構

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

指定依附元件

以 Go 編寫的 Cloud Run 函式必須透過 Go 模組和 go.mod 檔案,或 vendor 目錄提供所有依附元件。詳情請參閱在 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
}