É possível acionar funções em execução no local enviando a elas solicitações HTTP encaminhadas
por um processo de exibição local.
Verifique onde a função está sendo executada localmente verificando o URL exibido
quando você começou a executar a função. Por
padrão, a função será hospedada em localhost:8080.
Funções HTTP
Quando você testa a função HTTP no ambiente de desenvolvimento, ela normalmente
detecta solicitações em localhost:8080. Essa interface só pode ser acessada por meio da
máquina ou VM em que a função está sendo executada. As solicitações enviadas de outros sistemas
não conseguem acessá-la. Por esse motivo, é necessário emitir a solicitação HTTP no
mesmo sistema em que a função está sendo executada. Nos exemplos a seguir, se a
função estiver fazendo detecções em uma porta diferente de 8080, substitua 8080 no
exemplo pelo número da porta da função.
Como testar funções HTTP com o Cloud Shell
Se você estiver usando o Cloud Shell para criar e testar sua função, inicie-a
localmente na janela do terminal do Cloud Shell e emita a solicitação de
gatilho HTTP de um navegador ou de uma instância curl da seguinte maneira:
Navegador
Clique no ícone
na barra de ferramentas do Cloud Shell e selecione porta 8080 ou Alterar porta para
escolher uma porta diferente. Isso abre uma janela do navegador no sistema correto e
emite uma solicitação GET para a porta indicada.
Curl
Para controlar o formato da solicitação HTTP ou ver a resposta não formatada,
use curl:
Clique no ícone + na barra de menus do Cloud Shell para abrir uma nova janela de
terminal no mesmo sistema em que a função está sendo executada.
Nessa janela, execute o comando curl para acionar a função.
Exemplo:
curl localhost:8080
Como testar funções HTTP no servidor da área de trabalho
Se você estiver criando e executando a função no sistema da área de trabalho local, primeiro
inicie-a localmente e, em seguida, emita a solicitação de gatilho HTTP de um navegador
ou de uma instância curl da seguinte maneira:
Navegador
Abra uma nova janela ou guia do navegador e digite http://localhost:8080 na
barra de endereço. Isso abre uma janela do navegador para localhost:8080 no
servidor da área de trabalho a fim de acionar a função.
Curl
Abra uma nova janela de terminal na área de trabalho local e execute o comando curl
nela para acionar a função. Exemplo:
curl localhost:8080
Isso executa o comando curl especificado para acionar a função e exibe
a resposta não formatada.
Funções do CloudEvent
É possível enviar eventos de amostra para
Funções do CloudEvent
usando curl. As seguintes solicitações curl mostram como enviar eventos de amostra do
Cloud Pub/Sub e do
Cloud Storage para uma
função do CloudEvent em execução em localhost:8080.
É possível enviar eventos de amostra para
funções em segundo plano
usando curl. As seguintes solicitações curl mostram como enviar eventos de amostra do
Cloud Pub/Sub e do
Cloud Storage a uma
função de segundo plano em execução em localhost:8080.
[[["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-01-31 UTC."],[[["\u003cp\u003eLocally running functions can be triggered by sending HTTP requests through a local serving process, typically hosted at \u003ccode\u003elocalhost:8080\u003c/code\u003e, accessible only from the machine or VM where the function is running.\u003c/p\u003e\n"],["\u003cp\u003eHTTP functions can be tested using a browser by navigating to \u003ccode\u003ehttp://localhost:8080\u003c/code\u003e or with the \u003ccode\u003ecurl\u003c/code\u003e command in a terminal window on the same system where the function is running.\u003c/p\u003e\n"],["\u003cp\u003eCloudEvent functions can be tested by sending sample events via \u003ccode\u003ecurl\u003c/code\u003e, with examples provided for Cloud Pub/Sub and Cloud Storage events, including specific header and data formatting.\u003c/p\u003e\n"],["\u003cp\u003eBackground functions, similar to CloudEvent functions, can also be tested with \u003ccode\u003ecurl\u003c/code\u003e, using specific \u003ccode\u003eeventId\u003c/code\u003e, \u003ccode\u003etimestamp\u003c/code\u003e, \u003ccode\u003eeventType\u003c/code\u003e, and \u003ccode\u003eresource\u003c/code\u003e in the context data, along with sample Pub/Sub and Storage event data.\u003c/p\u003e\n"],["\u003cp\u003eThe use of \u003ccode\u003ecurl\u003c/code\u003e allows for control over the format of HTTP requests and unformatted responses, and other tools like Postman can be used to test the functions.\u003c/p\u003e\n"]]],[],null,["# Call local functions\n====================\n\nSetup\n-----\n\nThis document assumes that you've\n[set up a locally running function](/functions/1stgendocs/running/overview) on\n`localhost` using either [Functions Framework](/functions/1stgendocs/running/function-frameworks)\nor [Buildpacks](/functions/1stgendocs/running/overview). It also assumes that you've\ninstalled the `curl` tool on your local machine.\n| **Note:** while some operating systems include `curl` by default, others (such as Windows) do not. See [this page](https://curl.haxx.se/download.html) for instructions on how to install `curl` on your machine. Alternatively, you can also use other HTTP testing tools such as [Postman](https://postman.com/downloads) to test your functions.\n\nSending requests to local functions\n-----------------------------------\n\nYou can trigger locally-running functions by sending them HTTP requests routed\nvia a local serving process.\n\nDetermine where your function is running locally by checking the URL displayed\nwhen you started [running the function](/functions/1stgendocs/running/overview). By\ndefault, your function will be hosted at `localhost:8080`.\n\n### HTTP functions\n\nWhen you test your HTTP function from your development environment, it normally\nlistens for requests on `localhost:8080`. This interface is only accessible from\nthe machine or VM your function is running on; requests sent from any other\nsystem can't reach it. For this reason, you must issue the HTTP request from the\nsame system that your function is running on. In the following examples, if your\nfunction is listening on a port other than *8080* , replace the *8080* in the\nexample with the port number for your function.\n\n#### Testing HTTP functions with Cloud Shell\n\nIf you're using Cloud Shell to build and test your function, start your\nfunction locally in the Cloud Shell terminal window, then issue the HTTP\ntrigger request from a browser or `curl` instance as follows: \n\n### Browser\n\n\nClick the icon\non your cloud shell toolbar and choose *port 8080* or *Change port* to\npick a different port. This opens a browser window on the correct system and\nissues a GET request to the indicated port.\n\n### Curl\n\nTo control the format of your HTTP request or to see the unformatted reply,\nuse `curl`:\n\n1. Click the **+** icon on the Cloud Shell menu bar to open a new terminal window on the same system your function is running on.\n2. From within that window, run the `curl` command to trigger your function.\n For example:\n\n curl localhost:8080\n\n#### Testing HTTP functions on your desktop server\n\nIf you're building and running your function on your local desktop system, first\nstart your function locally, then issue your HTTP trigger request from a browser\nor `curl` instance as follows: \n\n### Browser\n\n\nOpen a new browser window or tab and type `http://localhost:8080` into the\nbrowser address bar. This opens a browser window to `localhost:8080` on your\ndesktop server to trigger your function.\n\n### Curl\n\n\nOpen a new terminal window on your local desktop, then run the `curl` command\nin that window to trigger your function. For example: \n\n curl localhost:8080\n\nThis runs the specified `curl` command to trigger your function and displays\nthe unformatted response.\n\n### CloudEvent functions\n\nYou can send sample events to\n[CloudEvent functions](/functions/1stgendocs/writing/write-event-driven-functions#cloudevent-functions)\nusing `curl`. The following `curl` requests show how to send sample\n[Cloud Pub/Sub](/functions/1stgendocs/calling/pubsub) and\n[Cloud Storage](/functions/1stgendocs/calling/storage) events to a\nCloudEvent function running at `localhost:8080`. \n\n### Pub/Sub\n\n```bash\ncurl localhost:8080 \\\n -X POST \\\n -H \"Content-Type: application/json\" \\\n -H \"ce-id: 123451234512345\" \\\n -H \"ce-specversion: 1.0\" \\\n -H \"ce-time: 2020-01-02T12:34:56.789Z\" \\\n -H \"ce-type: google.cloud.pubsub.topic.v1.messagePublished\" \\\n -H \"ce-source: //pubsub.googleapis.com/projects/MY-PROJECT/topics/MY-TOPIC\" \\\n -d '{\n \"message\": {\n \"data\": \"d29ybGQ=\",\n \"attributes\": {\n \"attr1\":\"attr1-value\"\n }\n },\n \"subscription\": \"projects/MY-PROJECT/subscriptions/MY-SUB\"\n }'\n \n```\n| **Note:** `data` values from [Cloud Pub/Sub events](/functions/1stgendocs/calling/pubsub) have `base64`-encoded `data` values. Functions that need access to the original Cloud Pub/Sub message's `data` value are expected to perform this decoding. In this example, `base64`-encoding the word `world` gives us `d29ybGQ=`.\n\n### Storage\n\n```bash\ncurl localhost:8080 \\\n -X POST \\\n -H \"Content-Type: application/json\" \\\n -H \"ce-id: 123451234512345\" \\\n -H \"ce-specversion: 1.0\" \\\n -H \"ce-time: 2020-01-02T12:34:56.789Z\" \\\n -H \"ce-type: google.cloud.storage.object.v1.finalized\" \\\n -H \"ce-source: //storage.googleapis.com/projects/_/buckets/MY-BUCKET-NAME\" \\\n -H \"ce-subject: objects/MY_FILE.txt\" \\\n -d '{\n \"bucket\": \"MY_BUCKET\",\n \"contentType\": \"text/plain\",\n \"kind\": \"storage#object\",\n \"md5Hash\": \"...\",\n \"metageneration\": \"1\",\n \"name\": \"MY_FILE.txt\",\n \"size\": \"352\",\n \"storageClass\": \"MULTI_REGIONAL\",\n \"timeCreated\": \"2020-04-23T07:38:57.230Z\",\n \"timeStorageClassUpdated\": \"2020-04-23T07:38:57.230Z\",\n \"updated\": \"2020-04-23T07:38:57.230Z\"\n }'\n \n```\n| **Note:** The `data` value in the example above contains the most commonly-used attributes of a Cloud Storage Object event. See the [Cloud Storage Object reference](/storage/docs/json_api/v1/objects#resource) for a complete list of Cloud Storage object properties.\n\n### Background functions\n\nYou can send sample events to\n[background functions](/functions/1stgendocs/writing/write-event-driven-functions#background-functions)\nusing `curl`. The following `curl` requests show how to send sample\n[Cloud Pub/Sub](/functions/1stgendocs/calling/pubsub) and\n[Cloud Storage](/functions/1stgendocs/calling/storage) events to a\nbackground function running at `localhost:8080`. \n\n### Pub/Sub\n\n```bash\n# 'world' base64-encoded is 'd29ybGQ='\ncurl localhost:8080 \\\n -X POST \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"context\": {\n \"eventId\":\"1144231683168617\",\n \"timestamp\":\"2020-05-06T07:33:34.556Z\",\n \"eventType\":\"google.pubsub.topic.publish\",\n \"resource\":{\n \"service\":\"pubsub.googleapis.com\",\n \"name\":\"projects/sample-project/topics/gcf-test\",\n \"type\":\"type.googleapis.com/google.pubsub.v1.PubsubMessage\"\n }\n },\n \"data\": {\n \"@type\": \"type.googleapis.com/google.pubsub.v1.PubsubMessage\",\n \"attributes\": {\n \"attr1\":\"attr1-value\"\n },\n \"data\": \"d29ybGQ=\"\n }\n }'\n \n```\n| **Note:** `data` values from [Cloud Pub/Sub events](/functions/1stgendocs/calling/pubsub) are sent to the function as `base64`-encoded strings.\n\n### Storage\n\n```bash\ncurl localhost:8080 \\\n -X POST \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"context\": {\n \"eventId\": \"1147091835525187\",\n \"timestamp\": \"2020-04-23T07:38:57.772Z\",\n \"eventType\": \"google.storage.object.finalize\",\n \"resource\": {\n \"service\": \"storage.googleapis.com\",\n \"name\": \"projects/_/buckets/MY_BUCKET/MY_FILE.txt\",\n \"type\": \"storage#object\"\n }\n },\n \"data\": {\n \"bucket\": \"MY_BUCKET\",\n \"contentType\": \"text/plain\",\n \"kind\": \"storage#object\",\n \"md5Hash\": \"...\",\n \"metageneration\": \"1\",\n \"name\": \"MY_FILE.txt\",\n \"size\": \"352\",\n \"storageClass\": \"MULTI_REGIONAL\",\n \"timeCreated\": \"2020-04-23T07:38:57.230Z\",\n \"timeStorageClassUpdated\": \"2020-04-23T07:38:57.230Z\",\n \"updated\": \"2020-04-23T07:38:57.230Z\"\n }\n }'\n \n```\n| **Note:** The `data` value in the example above contains the most commonly-used attributes of a Cloud Storage Object event. See the [Cloud Storage Object reference](/storage/docs/json_api/v1/objects#resource) for a complete list of Cloud Storage object properties."]]