Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Chamar funções do Cloud Run diretamente
Para oferecer suporte à iteração e depuração rápidas, as funções do Cloud Run fornecem um comando call na interface de linha de comando e a funcionalidade de teste na UIGoogle Cloud . Isso permite invocar diretamente uma função para garantir que ela esteja se comportando conforme o esperado. Isso faz a função ser executada
imediatamente, mesmo que possa ter sido implantada para responder a um
evento específico.
Testar a função com a CLI do Google Cloud
Para invocar diretamente uma função usando a gcloud CLI, use o
comando gcloud functions call e forneça os dados que a função espera
como JSON no argumento --data. Exemplo:
No campo Configurar evento acionador, insira todos os dados esperados pela função como JSON.
Clique em Testar a função.
A resposta da função é exibida no campo Saída, e os registros da execução individual aparecem no campo Registros.
Exemplo de função orientada a eventos do Cloud Pub/Sub
Este exemplo mostra como invocar diretamente uma função orientada a eventos acionada por
eventos do Cloud Pub/Sub:
Node.js
/** * Background Cloud Function to be triggered by Pub/Sub. * This function is exported by index.js, and executed when * the trigger topic receives a message. * * @param {object} message The Pub/Sub message. * @param {object} context The event metadata. */exports.helloPubSub=(message,context)=>{constname=message.data?Buffer.from(message.data,'base64').toString():'World';console.log(`Hello, ${name}!`);};
Python
defhello_pubsub(event,context):"""Background Cloud Function to be triggered by Pub/Sub. Args: event (dict): The dictionary with data specific to this type of event. The `@type` field maps to `type.googleapis.com/google.pubsub.v1.PubsubMessage`. The `data` field maps to the PubsubMessage data in a base64-encoded string. The `attributes` field maps to the PubsubMessage attributes if any is present. context (google.cloud.functions.Context): Metadata of triggering event including `event_id` which maps to the PubsubMessage messageId, `timestamp` which maps to the PubsubMessage publishTime, `event_type` which maps to `google.pubsub.topic.publish`, and `resource` which is a dictionary that describes the service API endpoint pubsub.googleapis.com, the triggering topic's name, and the triggering event type `type.googleapis.com/google.pubsub.v1.PubsubMessage`. Returns: None. The output is written to Cloud Logging. """importbase64print("""This Function was triggered by messageId {} published at {} to {} """.format(context.event_id,context.timestamp,context.resource["name"]))if"data"inevent:name=base64.b64decode(event["data"]).decode("utf-8")else:name="World"print(f"Hello {name}!")
Go
// Package helloworld provides a set of Cloud Functions samples.packagehelloworldimport("context""log")// 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 Pub/Sub message.funcHelloPubSub(ctxcontext.Context,mPubSubMessage)error{name:=string(m.Data)// Automatically decoded from base64.ifname==""{name="World"}log.Printf("Hello, %s!",name)returnnil}
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);}
Para invocar a função diretamente, envie um
PubsubMessage,
que espera dados codificados em base64, como os dados do evento:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-05 UTC."],[[["\u003cp\u003eCloud Run functions can be directly invoked using the \u003ccode\u003egcloud functions call\u003c/code\u003e command or through the Google Cloud console for testing and debugging purposes.\u003c/p\u003e\n"],["\u003cp\u003eWhen using the \u003ccode\u003egcloud functions call\u003c/code\u003e command, function input data is provided as JSON via the \u003ccode\u003e--data\u003c/code\u003e argument, which is interpreted as the body of a POST request for HTTP functions or as direct event data for background and CloudEvent functions.\u003c/p\u003e\n"],["\u003cp\u003eDirect function invocations are primarily for testing and are subject to limited quotas, hence not recommended for production use.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Cloud console allows testing functions by entering expected JSON data in the "Configure Triggering Event" field and viewing the function's response in the "Output" field.\u003c/p\u003e\n"],["\u003cp\u003eEvent driven functions such as Cloud Pub/Sub function can be invoked directly by passing a base64 encoded \u003ccode\u003ePubsubMessage\u003c/code\u003e as the event data, with examples of how to achieve this in Node.js, Python, Go, Java, C#, Ruby and PHP.\u003c/p\u003e\n"]]],[],null,["# Call Cloud Run functions directly\n=================================\n\nTo support quick iteration and debugging, Cloud Run functions provides a\n`call` command in the command-line interface and testing functionality in the\nGoogle Cloud console UI. This allows you to directly invoke a function to\nensure it is behaving as expected. This causes the function to execute\nimmediately, even though it may have been deployed to respond to a\nspecific event.\n| **Note:** Direct function invocations use the [call method](/functions/docs/reference/rest/v1/projects.locations.functions/call). This method has a limited [quota](/functions/quotas) that cannot be increased. It is intended for testing and shouldn't be used in production.\n\nTest your function with Google Cloud CLI\n----------------------------------------\n\nTo directly invoke a function using the gcloud CLI, use\nthe `gcloud functions call` command and supply any data your function expects\nas JSON in the `--data` argument. For example: \n\n```bash\ngcloud functions call YOUR_FUNCTION_NAME --data '{\"name\":\"Tristan\"}'\n```\n\nwhere \u003cvar translate=\"no\"\u003eYOUR_FUNCTION_NAME\u003c/var\u003e is the name of the function\nyou want to execute. The `--data` argument is sent to your function as follows:\n\n- **For HTTP functions,** the data you supply is sent as the body of a POST request.\n- **For background functions,** the data is passed directly as the event data to your function.\n- **For CloudEvent functions,** the data is passed directly as the event data to your function.\n\nFor more information, see the [`gcloud functions call`](/sdk/gcloud/reference/functions/call) documentation.\n\nTest your function with the Google Cloud Console\n------------------------------------------------\n\nTo directly invoke a function from the Google Cloud console,\nfollow these steps:\n\n1. [Go to the Cloud Run functions Overview page](https://console.cloud.google.com/functions/list).\n\n2. Click the name of the function you want to invoke.\n\n3. Click the **Testing** tab.\n\n4. In the **Configure Triggering Event** field,\n enter any data your function expects as JSON.\n\n5. Click **Test the function**.\n\nYour function's response appears in the **Output** field, and logs for the\nindividual execution appear in the **Logs** field.\n\nCloud Pub/Sub event-driven function example\n-------------------------------------------\n\nThis example shows how to directly invoke an event-driven function\ntriggered by Cloud Pub/Sub events: \n\n### Node.js\n\n /**\n * Background Cloud Function to be triggered by Pub/Sub.\n * This function is exported by index.js, and executed when\n * the trigger topic receives a message.\n *\n * @param {object} message The Pub/Sub message.\n * @param {object} context The event metadata.\n */\n exports.helloPubSub = (message, context) =\u003e {\n const name = message.data\n ? Buffer.from(message.data, 'base64').toString()\n : 'World';\n\n console.log(`Hello, ${name}!`);\n };\n\n### Python\n\n def hello_pubsub(event, context):\n \"\"\"Background Cloud Function to be triggered by Pub/Sub.\n Args:\n event (dict): The dictionary with data specific to this type of\n event. The `@type` field maps to\n `type.googleapis.com/google.pubsub.v1.PubsubMessage`.\n The `data` field maps to the PubsubMessage data\n in a base64-encoded string. The `attributes` field maps\n to the PubsubMessage attributes if any is present.\n context (google.cloud.functions.Context): Metadata of triggering event\n including `event_id` which maps to the PubsubMessage\n messageId, `timestamp` which maps to the PubsubMessage\n publishTime, `event_type` which maps to\n `google.pubsub.topic.publish`, and `resource` which is\n a dictionary that describes the service API endpoint\n pubsub.googleapis.com, the triggering topic's name, and\n the triggering event type\n `type.googleapis.com/google.pubsub.v1.PubsubMessage`.\n Returns:\n None. The output is written to Cloud Logging.\n \"\"\"\n import base64\n\n print(\n \"\"\"This Function was triggered by messageId {} published at {} to {}\n \"\"\".format(\n context.event_id, context.timestamp, context.resource[\"name\"]\n )\n )\n\n if \"data\" in event:\n name = base64.b64decode(event[\"data\"]).decode(\"utf-8\")\n else:\n name = \"World\"\n print(f\"Hello {name}!\")\n\n### Go\n\n\n // Package helloworld provides a set of Cloud Functions samples.\n package helloworld\n\n import (\n \t\"context\"\n \t\"log\"\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 Pub/Sub message.\n func HelloPubSub(ctx context.Context, m PubSubMessage) error {\n \tname := string(m.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\n import com.google.cloud.functions.BackgroundFunction;\n import com.google.cloud.functions.Context;\n import functions.eventpojos.PubsubMessage;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n import java.util.logging.Level;\n import java.util.logging.Logger;\n\n public class HelloPubSub implements BackgroundFunction\u003cPubsubMessage\u003e {\n private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());\n\n @Override\n public void accept(PubsubMessage message, Context context) {\n String name = \"world\";\n if (message != null && message.getData() != null) {\n name = new String(\n Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),\n StandardCharsets.UTF_8);\n }\n logger.info(String.format(\"Hello %s!\", name));\n return;\n }\n }\n\n### C#\n\n```c#\nusing CloudNative.CloudEvents;\nusing Google.Cloud.Functions.Framework;\nusing Google.Events.Protobuf.Cloud.PubSub.V1;\nusing Microsoft.Extensions.Logging;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace HelloPubSub;\n\npublic 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\n### Ruby\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\n### PHP\n\n```php\nuse CloudEvents\\V1\\CloudEventInterface;\nuse 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.\nFunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');\n\nfunction 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\nTo invoke the function directly, send a\n[`PubsubMessage`](/pubsub/docs/reference/rest/v1/PubsubMessage),\nwhich expects base64-encoded data, as the event data: \n\n### Node.js\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call helloPubSub --data '{\"data\":\"'$DATA'\"}'\n```\n\n### Python\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{\"data\":\"'$DATA'\"}'\n```\n\n### Go\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call HelloPubSub --data '{\"data\":\"'$DATA'\"}'\n```\n\n### Java\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call java-hello-pubsub --data '{\"data\":\"'$DATA'\"}'\n```\n\n### C#\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call csharp-hello-pubsub --data '{\"data\":\"'$DATA'\"}'\n```\n\n### Ruby\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{\"data\":\"'$DATA'\"}'\n```\n\n### PHP\n\n```bash\nDATA=$(printf 'Hello!'|base64) && gcloud functions call helloworldPubsub --data '{\"data\":\"'$DATA'\"}'\n```\n\nThis CLI example uses `bash` or `sh` syntax. It works in Linux and Mac\nenvironments but not Windows.\n\nYou can also invoke the function from the Google Cloud console by using the\nsame event data in the **Triggering event** field."]]