Cloud Pub/Sub (2nd Gen)
Stay organized with collections
Save and categorize content based on your preferences.
Process a Cloud Pub/Sub message using Cloud Functions (2nd Gen) and Eventarc
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis document demonstrates how to process Cloud Pub/Sub messages using Cloud Functions (2nd Gen) and Eventarc.\u003c/p\u003e\n"],["\u003cp\u003eCode examples are provided in C#, Go, Java, Node.js, PHP, Python, and Ruby, showing how to handle Pub/Sub messages within a Cloud Function.\u003c/p\u003e\n"],["\u003cp\u003eEach code example showcases the extraction and decoding of message data from Pub/Sub messages received via CloudEvents.\u003c/p\u003e\n"],["\u003cp\u003eThe document also directs to documentation regarding authenticating to Cloud Run functions using Application Default Credentials.\u003c/p\u003e\n"],["\u003cp\u003eThe content is focused on a practical method of triggering functions from Pub/Sub with use of Eventarc, and covers a variety of programming languages.\u003c/p\u003e\n"]]],[],null,["# Cloud Pub/Sub (2nd Gen)\n\nProcess a Cloud Pub/Sub message using Cloud Functions (2nd Gen) and Eventarc\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Locally test your function](/functions/docs/running/direct)\n- [The Go Runtime](/functions/1stgendocs/concepts/go-runtime)\n- [The Go runtime](/run/docs/runtimes/go)\n- [Trigger functions from Pub/Sub using Eventarc](/run/docs/tutorials/pubsub-eventdriven)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using CloudNative.CloudEvents;\n using Google.Cloud.Functions.Framework;\n using Google.Events.Protobuf.Cloud.PubSub.V1;\n using Microsoft.Extensions.Logging;\n using System.Threading;\n using System.Threading.Tasks;\n\n namespace HelloPubSub;\n\n public class Function : ICloudEventFunction\u003cMessagePublishedData\u003e\n {\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)\n {\n string nameFromMessage = data.Message?.TextData;\n string name = string.IsNullOrEmpty(nameFromMessage) ? \"world\" : nameFromMessage;\n _logger.LogInformation(\"Hello {name}\", name);\n return Task.CompletedTask;\n }\n }\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\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 }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.CloudEventsFunction;\n import com.google.gson.Gson;\n import functions.eventpojos.PubSubBody;\n import io.cloudevents.CloudEvent;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n import java.util.logging.Logger;\n\n public class SubscribeToTopic implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(SubscribeToTopic.class.getName());\n\n @Override\n public void accept(CloudEvent event) {\n // The Pub/Sub message is passed as the CloudEvent's data payload.\n if (event.getData() != null) {\n // Extract Cloud Event data and convert to PubSubBody\n String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);\n Gson gson = new Gson();\n PubSubBody body = gson.fromJson(cloudEventData, PubSubBody.class);\n // Retrieve and decode PubSub message data\n String encodedData = body.getMessage().getData();\n String decodedData =\n new String(Base64.getDecoder().decode(encodedData), StandardCharsets.UTF_8);\n logger.info(\"Hello, \" + decodedData + \"!\");\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n // Register a CloudEvent callback with the Functions Framework that will\n // be executed when the Pub/Sub trigger topic receives a message.\n functions.cloudEvent('helloPubSub', cloudEvent =\u003e {\n // The Pub/Sub message is passed as the CloudEvent's data payload.\n const base64name = cloudEvent.data.message.data;\n\n const name = base64name\n ? Buffer.from(base64name, 'base64').toString()\n : 'World';\n\n console.log(`Hello, ${name}!`);\n });\n\n### PHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use CloudEvents\\V1\\CloudEventInterface;\n use Google\\CloudFunctions\\FunctionsFramework;\n\n // Register the function with Functions Framework.\n // This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment\n // variable when deploying. The `FUNCTION_TARGET` environment variable should\n // match the first parameter.\n FunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');\n\n function helloworldPubsub(CloudEventInterface $event): void\n {\n $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n\n $cloudEventData = $event-\u003egetData();\n $pubSubData = base64_decode($cloudEventData['message']['data']);\n\n $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World';\n fwrite($log, \"Hello, $name!\" . PHP_EOL);\n }\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import base64\n\n from cloudevents.http import CloudEvent\n import functions_framework\n\n\n # Triggered from a message on a Cloud Pub/Sub topic.\n @functions_framework.cloud_event\n def subscribe(cloud_event: CloudEvent) -\u003e None:\n # Print out the data from Pub/Sub, to prove that it worked\n print(\n \"Hello, \" + base64.b64decode(cloud_event.data[\"message\"][\"data\"]).decode() + \"!\"\n )\n\n### Ruby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n require \"base64\"\n\n FunctionsFramework.cloud_event \"hello_pubsub\" do |event|\n # The event parameter is a CloudEvents::Event::V1 object.\n # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html\n name = Base64.decode64 event.data[\"message\"][\"data\"] rescue \"World\"\n\n # A cloud_event function does not return a response, but you can log messages\n # or cause side effects such as sending additional events.\n logger.info \"Hello, #{name}!\"\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]