Crie e implemente uma função HTTP do Cloud Run com Node.js (1.ª geração)
Este guia explica o processo de escrita de uma função do Cloud Run com o tempo de execução do Node.js. Existem dois tipos de funções do Cloud Run:
- Uma função HTTP, que invoca a partir de pedidos HTTP padrão.
- Uma função orientada por eventos, que usa para processar eventos da sua infraestrutura do Google Cloud, como mensagens num tópico Pub/Sub ou alterações num contentor do Cloud Storage.
O exemplo mostra como criar uma função HTTP simples.
Antes de começar
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles. -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles. - Instale e inicialize a CLI gcloud.
- Atualize e instale os componentes do
gcloud
:gcloud components update
- Prepare o seu ambiente de desenvolvimento.
Crie um diretório no seu sistema local para o código da função:
Linux ou Mac OS X
mkdir ~/helloworld cd ~/helloworld
Windows
mkdir %HOMEPATH%\helloworld cd %HOMEPATH%\helloworld
Crie um ficheiro
index.js
no diretóriohelloworld
com o seguinte conteúdo:Esta função de exemplo recebe um nome fornecido no pedido HTTP e devolve uma saudação ou "Olá, mundo!" quando não é fornecido nenhum nome.
Para criar o ficheiro de dependências
package.json
com onpm
, execute estes comandos:npm init npm install c8 gaxios mocha sinon supertest wait-port --save-dev npm install @google-cloud/functions-framework escape-html
Se preferir criar o ficheiro
package.json
manualmente, crie um ficheiropackage.json
no diretóriohelloworld
com o seguinte conteúdo:Quando a implementação da função terminar, tome nota da propriedade
httpsTrigger.url
ou encontre-a através do seguinte comando:gcloud functions describe helloHttp
Deve ter esta forma:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
Visite este URL no seu navegador. Deverá ver a mensagem "Hello World!".
Experimente transmitir um nome no pedido HTTP, por exemplo, usando o seguinte URL:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME
Deverá ver a mensagem "Olá
NAME
!"
Crie uma função
Especifique dependências
As dependências no Node.js são armazenadas num ficheiro denominado
package.json
.
Pode criar este ficheiro manualmente ou com o comando
npm.
Implemente a função
Para implementar a função com um acionador HTTP, execute o seguinte comando no diretório helloworld
:
gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated
A flag --allow-unauthenticated
permite-lhe aceder à função sem autenticação.
Para exigir a autenticação, omita a flag.
Teste a função
Ver registos
Os registos das funções do Cloud Run são visíveis através da CLI gcloud e na IU do Cloud Logging.
Use a ferramenta de linha de comandos
Para ver os registos da sua função com a CLI gcloud, use o comando
logs read
, seguido do nome da função:
gcloud functions logs read helloHttp
O resultado deve ser semelhante ao seguinte:
LEVEL NAME EXECUTION_ID TIME_UTC LOG D helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started D helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200
Use o painel de controlo de registo
Também pode ver os registos das funções do Cloud Run a partir da Google Cloud consola.