直接调用 Cloud Functions 函数
为了支持快速迭代和调试,Cloud Functions 在命令行界面中提供了一个 call
命令,并在 Google Cloud 控制台界面中提供了测试功能。这样,您就可以直接调用函数,确保其行为符合预期。在这种情况下,函数会立即执行,即使它可能是为响应特定事件而部署的也是如此。
使用 Google Cloud CLI 测试您的函数
第 1 代
要使用 gcloud CLI 直接调用第 1 代函数,请使用 gcloud functions call
命令并在 --data
参数中以 JSON 格式提供函数所需的任何数据。例如:
gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Tristan"}'
其中,YOUR_FUNCTION_NAME
是您要执行的函数的名称。--data
是发送给您的函数的参数,如下所示:
- 对于 HTTP 函数,您提供的数据将以 POST 请求正文的形式发送。
- 对于后台函数,数据将以事件数据形式直接传递给您的函数。 如需详细了解如何在后台函数中访问事件数据,请参阅后台函数参数。
- 对于 CloudEvent 函数,数据将以事件数据形式直接传递给您的函数。如需详细了解如何在 CloudEvent 函数中访问事件数据,请参阅 CloudEvent 函数参数。
第 2 代
如需使用 gcloud CLI 直接调用第 2 代函数,请使用 gcloud functions call
的第 2 代版本,并在 --data
参数中以 JSON 格式提供函数所需的任何数据。例如:
gcloud functions call YOUR_FUNCTION_NAME \
--region=REGION --gen2 \
--data '{"name":"Kalani"}'
您需要将其中的:
- YOUR_FUNCTION_NAME:您要测试的函数的名称
- REGION:将您的函数部署到的 Google Cloud 区域
--data
是发送给您的函数的参数,如下所示:
- 对于 HTTP 函数,您提供的数据将以 POST 请求正文的形式发送。
- 对于 CloudEvent 函数,数据将以事件数据形式直接传递给您的函数。如需详细了解如何在 CloudEvent 函数中访问事件数据,请参阅 CloudEvent 函数参数。
如需了解详情,请参阅 gcloud functions call
文档。
使用 Google Cloud Console 测试您的函数
如需通过 Google Cloud 控制台直接调用函数,请按以下步骤操作:
第 1 代
点击要调用的函数的名称。
点击测试标签。
在配置触发事件字段中,以 JSON 格式输入函数所需的任何数据。
点击测试函数。
函数的响应显示在输出字段中,单项执行的日志显示在日志字段中。
第 2 代
从列表中点击要调用的函数的名称。 此时将转到函数详情 (Function details) 页面。
点击测试标签。
在配置触发事件字段中,以 JSON 格式输入函数所需的任何数据。
点击 +添加查询参数和 +添加标头参数按钮,根据需要向函数调用添加查询和标头参数。
Google Cloud 控制台会将您指定的参数汇编到 CLI 测试命令窗口中的
gcloud functions call
命令。选择在 Cloud Shell 中运行,以打开 Cloud Shell 窗口来运行此命令。
在 Cloud Shell 窗口中显示的
gcloud functions call
命令触发后按 Enter 键。
Cloud Pub/Sub 事件驱动的函数示例
本示例演示了如何直接调用由 Cloud Pub/Sub 事件触发的第 1 代事件驱动函数:
Node.js
Python
Go
Java
C#
Ruby
PHP
如需直接调用该函数,请以事件数据的形式发送 PubsubMessage
,该消息应为采用 base64 编码的数据:
Node.js
DATA=$(printf 'Hello!'|base64) && gcloud functions call helloPubSub --data '{"data":"'$DATA'"}'
Python
DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'
Go
DATA=$(printf 'Hello!'|base64) && gcloud functions call HelloPubSub --data '{"data":"'$DATA'"}'
Java
DATA=$(printf 'Hello!'|base64) && gcloud functions call java-hello-pubsub --data '{"data":"'$DATA'"}'
C#
DATA=$(printf 'Hello!'|base64) && gcloud functions call csharp-hello-pubsub --data '{"data":"'$DATA'"}'
Ruby
DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'
PHP
DATA=$(printf 'Hello!'|base64) && gcloud functions call helloworldPubsub --data '{"data":"'$DATA'"}'
此 CLI 示例使用 bash
或 sh
语法。它适用于 Linux 和 Mac 环境,但不适用于 Windows。
您还可以在触发事件字段中使用相同的事件数据,从 Google Cloud 控制台调用该函数。