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

  1. 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.
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. 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 the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. 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 the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. Instale e inicialize a CLI gcloud.
  9. Atualize e instale os componentes do gcloud:
    gcloud components update
  10. Prepare o seu ambiente de desenvolvimento.

    Aceda ao guia de configuração do Node.js

  11. Crie uma função

    1. 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
      
    2. Crie um ficheiro index.js no diretório helloworld com o seguinte conteúdo:

      const functions = require('@google-cloud/functions-framework');
      const escapeHtml = require('escape-html');
      
      /**
       * Responds to an HTTP request using data from the request body parsed according
       * to the "content-type" header.
       *
       * @param {Object} req Cloud Function request context.
       * @param {Object} res Cloud Function response context.
       */
      functions.http('helloHttp', (req, res) => {
        res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
      });

      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.

    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.

    • Para criar o ficheiro de dependências package.json com o npm, 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.jsonmanualmente, crie um ficheiro package.json no diretório helloworld com o seguinte conteúdo:

      {
        "name": "nodejs-docs-samples-functions-hello-world-http",
        "version": "0.0.1",
        "private": true,
        "license": "Apache-2.0",
        "author": "Google Inc.",
        "repository": {
          "type": "git",
          "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
        },
        "engines": {
          "node": ">=16.0.0"
        },
        "scripts": {
          "unit-test": "c8 mocha -p -j 2 test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=6000 --exit",
          "system-test": "c8 mocha -p -j 2 test/*system*test.js --timeout=600000 --exit",
          "all-test": "npm run unit-test && npm run system-test",
          "test": "npm -- run unit-test"
        },
        "dependencies": {
          "@google-cloud/functions-framework": "^3.1.0",
          "escape-html": "^1.0.3"
        },
        "devDependencies": {
          "c8": "^10.0.0",
          "gaxios": "^6.0.0",
          "mocha": "^10.0.0",
          "sinon": "^18.0.0",
          "supertest": "^7.0.0",
          "wait-port": "^1.0.4"
        }
      }
      

    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

    1. 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
    2. 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!"

    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.