constfunctions=require('@google-cloud/functions-framework');// Register a CloudEvent callback with the Functions Framework that will// be executed when the Pub/Sub trigger topic receives a message.functions.cloudEvent('helloPubSub',cloudEvent=>{// The Pub/Sub message is passed as the CloudEvent's data payload.constbase64name=cloudEvent.data.message.data;constname=base64name?Buffer.from(base64name,'base64').toString():'World';console.log(`Hello, ${name}!`);});
Python
importbase64fromcloudevents.httpimportCloudEventimportfunctions_framework# Triggered from a message on a Cloud Pub/Sub topic.@functions_framework.cloud_eventdefsubscribe(cloud_event:CloudEvent)-> None:# Print out the data from Pub/Sub, to prove that it workedprint("Hello, "+base64.b64decode(cloud_event.data["message"]["data"]).decode()+"!")
Go
// 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}
Java
importcom.google.cloud.functions.CloudEventsFunction;importcom.google.gson.Gson;importfunctions.eventpojos.PubSubBody;importio.cloudevents.CloudEvent;importjava.nio.charset.StandardCharsets;importjava.util.Base64;importjava.util.logging.Logger;publicclassSubscribeToTopicimplementsCloudEventsFunction{privatestaticfinalLoggerlogger=Logger.getLogger(SubscribeToTopic.class.getName());@Overridepublicvoidaccept(CloudEventevent){// The Pub/Sub message is passed as the CloudEvent's data payload.if(event.getData()!=null){// Extract Cloud Event data and convert to PubSubBodyStringcloudEventData=newString(event.getData().toBytes(),StandardCharsets.UTF_8);Gsongson=newGson();PubSubBodybody=gson.fromJson(cloudEventData,PubSubBody.class);// Retrieve and decode PubSub message dataStringencodedData=body.getMessage().getData();StringdecodedData=newString(Base64.getDecoder().decode(encodedData),StandardCharsets.UTF_8);logger.info("Hello, "+decodedData+"!");}}}
require"functions_framework"require"base64"FunctionsFramework.cloud_event"hello_pubsub"do|event|# The event parameter is a CloudEvents::Event::V1 object.# See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.htmlname=Base64.decode64event.data["message"]["data"]rescue"World"# A cloud_event function does not return a response, but you can log messages# or cause side effects such as sending additional events.logger.info"Hello, #{name}!"end
PHP
use CloudEvents\V1\CloudEventInterface;use Google\CloudFunctions\FunctionsFramework;// Register the function with Functions Framework.// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment// variable when deploying. The `FUNCTION_TARGET` environment variable should// match the first parameter.FunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');function helloworldPubsub(CloudEventInterface $event): void{ $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb'); $cloudEventData = $event->getData(); $pubSubData = base64_decode($cloudEventData['message']['data']); $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World'; fwrite($log, "Hello, $name!" . PHP_EOL);}
[[["易于理解","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-02-14。"],[[["\u003cp\u003eCloud Functions v2 API allows direct invocation of functions using the \u003ccode\u003egcloud functions call\u003c/code\u003e command for testing and debugging purposes.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003egcloud functions call\u003c/code\u003e command requires providing function-specific data as JSON within the \u003ccode\u003e--data\u003c/code\u003e argument.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003e--data\u003c/code\u003e argument's content is sent as the body of a POST request for HTTP functions and as the event data for CloudEvent functions.\u003c/p\u003e\n"],["\u003cp\u003eDirect function invocations are designed for testing, not production, and utilize a \u003ccode\u003ecall\u003c/code\u003e method with a limited, non-expandable quota.\u003c/p\u003e\n"],["\u003cp\u003eThe document gives examples of direct invocations for various programming languages such as Node.js, Python, Go, Java, C#, Ruby, and PHP.\u003c/p\u003e\n"]]],[],null,[]]