Go 執行階段

總覽

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

如要瞭解一般執行階段,以及各個 Go 執行階段使用的 Ubuntu 版本,請參閱 Cloud Run functions 執行環境

選取執行階段

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 開發環境」。

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

原始碼結構

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

指定依附元件

以 Go 編寫的 Cloud Run 函式必須透過含 go.mod 檔案的 Go 模組或 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
}