Jika Anda membuat fungsi baru, lihat Panduan Memulai Konsol di Cloud Run. Konten di halaman ini hanya berlaku untuk fungsi lama yang sudah ada yang dibuat dengan Cloud Functions v1 API.
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Runtime Go
Ringkasan
Fungsi Cloud Run Anda berjalan di lingkungan yang terdiri dari versi sistem operasi plus paket add-on, dukungan bahasa, dan library Functions Framework yang mendukung dan memanggil fungsi Anda.
Lingkungan ini diidentifikasi berdasarkan versi bahasa, dan dikenal sebagai runtime.
Untuk mengetahui informasi tentang runtime secara umum, dan untuk mempelajari versi Ubuntu yang digunakan setiap runtime Go, lihat lingkungan eksekusi fungsi Cloud Run.
Memilih runtime Anda
Fungsi Cloud Run mendukung beberapa versi Go, yang tercantum di halaman
Dukungan runtime. Anda dapat
memilih runtime Go pilihan untuk fungsi Anda selama deployment.
gcloud
Jika menggunakan Google Cloud CLI, tentukan runtime menggunakan parameter --runtime dengan runtime Go pilihan Anda.
Contoh:
FLAGS... merujuk pada argumen yang diteruskan selama deployment pertama fungsi Anda. Untuk mengetahui informasi selengkapnya mengenai argumen yang diperlukan dan opsional, lihat Men-deploy fungsi Cloud Run.
Anda dapat menyiapkan fungsi langsung dari konsol Google Cloud atau menulisnya di komputer lokal Anda, lalu menguploadnya. Guna menyiapkan mesin lokal Anda untuk pengembangan Go,
lihat Menyiapkan Lingkungan Pengembangan Go.
Untuk mulai menggunakan fungsi Go di Cloud Run dengan cepat, lihat Panduan memulai.
Struktur kode sumber
Agar fungsi Cloud Run dapat menemukan definisi fungsi Anda, kode sumber Anda harus mengikuti struktur tertentu. Lihat artikel Menulis Cloud Run Functions untuk mengetahui informasi selengkapnya.
Menentukan dependensi
Fungsi Cloud Run di Go harus menyediakan semua dependensinya dengan modul Go dan file go.mod, atau dengan direktori vendor. Untuk informasi selengkapnya,
lihat Menentukan dependensi di Go.
Variabel lingkungan
Runtime Go akan otomatis menetapkan variabel lingkungan tertentu untuk digunakan fungsi Anda sesuai kebutuhan. Untuk mengetahui detailnya, lihat Menggunakan Variabel Lingkungan.
Jenis Context
Paket context Go menentukan jenis Context, yang memiliki batas waktu, sinyal pembatalan, dan nilai cakupan permintaan
lainnya di seluruh batas API dan antar-proses.
Kode fungsi Cloud Run berikut menunjukkan contoh akses konteks oleh klien Pub/Sub:
// Package helloworld provides a set of Cloud Functions samples.packagehelloworldimport("context""fmt""log""github.com/GoogleCloudPlatform/functions-framework-go/functions""github.com/cloudevents/sdk-go/v2/event")funcinit(){functions.CloudEvent("HelloPubSub",helloPubSub)}// MessagePublishedData contains the full Pub/Sub message// See the documentation for more details:// https://cloud.google.com/eventarc/docs/cloudevents#pubsubtypeMessagePublishedDatastruct{MessagePubSubMessage}// PubSubMessage is the payload of a Pub/Sub event.// See the documentation for more details:// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessagetypePubSubMessagestruct{Data[]byte`json:"data"`}// helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.funchelloPubSub(ctxcontext.Context,eevent.Event)error{varmsgMessagePublishedDataiferr:=e.DataAs(&msg);err!=nil{returnfmt.Errorf("event.DataAs: %w",err)}name:=string(msg.Message.Data)// Automatically decoded from base64.ifname==""{name="World"}log.Printf("Hello, %s!",name)returnnil}
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-08-19 UTC."],[[["\u003cp\u003eCloud Run functions utilize a runtime environment that includes the operating system, language support, and the Functions Framework library.\u003c/p\u003e\n"],["\u003cp\u003eYou can choose a specific Go runtime version for your Cloud Run function during deployment, as listed in the Runtime support documentation.\u003c/p\u003e\n"],["\u003cp\u003eDependencies for Go Cloud Run functions must be provided via Go modules with a \u003ccode\u003ego.mod\u003c/code\u003e file or a \u003ccode\u003evendor\u003c/code\u003e directory.\u003c/p\u003e\n"],["\u003cp\u003eThe source code for Cloud Run functions needs to adhere to a defined structure to ensure the function's definition can be located correctly.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eContext\u003c/code\u003e type from Go's \u003ccode\u003econtext\u003c/code\u003e package is used within Cloud Run functions for managing deadlines, cancellation signals, and request-scoped values, as shown in the Pub/Sub example.\u003c/p\u003e\n"]]],[],null,["# The Go Runtime\n==============\n\nOverview\n--------\n\nYour Cloud Run function runs in an environment consisting of an operating\nsystem version plus add-on packages, language support, and\nthe Functions Framework library that supports and invokes your function.\nThis environment is identified by the language version, and is known as the\nruntime.\n\nFor information about runtimes in general, and to learn which Ubuntu version\neach Go runtime uses, see the\n[Cloud Run functions execution environment](/functions/1stgendocs/concepts/execution-environment#go).\n\nSelect your runtime\n-------------------\n\nCloud Run functions supports several versions of Go, listed on the\n[Runtime support](/functions/1stgendocs/runtime-support#go) page. You can\nselect the preferred Go runtime for your function during deployment. \n\n### gcloud\n\nIf you're using the Google Cloud CLI, specify the runtime\nby using the `--runtime` parameter with the Go runtime of your choice.\nFor example: \n\n```bash\ngcloud functions deploy FUNCTION_NAME --no-gen2 --runtime go121 FLAGS...\n```\n\n\u003cvar translate=\"no\"\u003eFLAGS\u003c/var\u003e`...` refers to arguments passed during the first\ndeployment of your function. For more information regarding required and\noptional arguments, see\n[Deploy a Cloud Run function](/functions/1stgendocs/deploy#basics).\n\n### Console\n\nIf you're using the Google Cloud console, see the\n[Google Cloud console quickstart](/functions/1stgendocs/console-quickstart-1st-gen) for\ndetailed instructions.\n\nFunction preparation\n--------------------\n\nYou can prepare a function directly from the Google Cloud console or write it on your\nlocal machine and upload it. To prepare your local machine for Go development,\nsee [Setting Up a Go Development Environment](/go/docs/setup).\n\nTo get started quickly with Go on Cloud Run functions, see the\n[Quickstart](/functions/1stgendocs/create-deploy-gcloud-1st-gen).\n\nSource code structure\n---------------------\n\nFor Cloud Run functions to find your function's definition, your\nsource code must follow a specific structure. See\n[Writing Cloud Run functions](/functions/1stgendocs/writing#structuring_source_code)\nfor more information.\n\nSpecifying dependencies\n-----------------------\n\nCloud Run functions in Go must provide all of their dependencies either with\nGo modules and a `go.mod` file, or with a `vendor` directory. For more information,\nsee [Specifying dependencies in Go](/functions/1stgendocs/writing/specifying-dependencies-go).\n\nEnvironment variables\n---------------------\n\nYour Go runtime automatically sets certain environment variables for your function\nto use as needed. For details, see\n[Using Environment Variables](/functions/1stgendocs/configuring/env-var#newer_runtimes).\n\n`Context` type\n--------------\n\n[Go's `context` package](https://golang.org/pkg/context/) defines the `Context`\ntype, which carries deadlines, cancellation signals, and other request-scoped\nvalues across API boundaries and between processes.\n\nThe following Cloud Run functions code shows an example of context access by a\nPub/Sub client: \n\n\n // Package helloworld provides a set of Cloud Functions samples.\n package helloworld\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n )\n\n func init() {\n \tfunctions.CloudEvent(\"HelloPubSub\", helloPubSub)\n }\n\n // MessagePublishedData contains the full Pub/Sub message\n // See the documentation for more details:\n // https://cloud.google.com/eventarc/docs/cloudevents#pubsub\n type MessagePublishedData struct {\n \tMessage PubSubMessage\n }\n\n // PubSubMessage is the payload of a Pub/Sub event.\n // See the documentation for more details:\n // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage\n type PubSubMessage struct {\n \tData []byte `json:\"data\"`\n }\n\n // helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.\n func helloPubSub(ctx context.Context, e event.Event) error {\n \tvar msg MessagePublishedData\n \tif err := e.DataAs(&msg); err != nil {\n \t\treturn fmt.Errorf(\"event.DataAs: %w\", err)\n \t}\n\n \tname := string(msg.Message.Data) // Automatically decoded from base64.\n \tif name == \"\" {\n \t\tname = \"World\"\n \t}\n \tlog.Printf(\"Hello, %s!\", name)\n \treturn nil\n }"]]