Go 的 context 软件包定义了 Context 类型,该类型跨 API 边界和在进程之间传递截止时限、取消信号以及其他请求范围的值。
以下 Cloud Run functions 代码展示了 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}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-04-10。"],[[["Cloud Run functions utilize a runtime environment that includes the operating system, language support, and the Functions Framework library."],["You can choose a specific Go runtime version for your Cloud Run function during deployment, as listed in the Runtime support documentation."],["Dependencies for Go Cloud Run functions must be provided via Go modules with a `go.mod` file or a `vendor` directory."],["The source code for Cloud Run functions needs to adhere to a defined structure to ensure the function's definition can be located correctly."],["The `Context` type from Go's `context` package is used within Cloud Run functions for managing deadlines, cancellation signals, and request-scoped values, as shown in the Pub/Sub example."]]],[]]