Crea ed esegui il deployment di una funzione Cloud Run HTTP utilizzando Node.js 1ª generazionen.)

Questa guida ti illustra la procedura per scrivere una funzione Cloud Run utilizzando il runtime Node.js. Esistono due tipi di funzioni Cloud Run:

  • Una funzione HTTP, che richiami da richieste HTTP standard.
  • Una funzione basata su eventi, che utilizzi per gestire gli eventi della tua infrastruttura cloud, ad esempio i messaggi in un argomento Pub/Sub o le modifiche in un bucket Cloud Storage.

L'esempio mostra come creare una semplice funzione HTTP.

Prima di iniziare

  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.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  8. Installa e inizializza gcloud CLI.
  9. Aggiorna e installa i componenti di gcloud:
    gcloud components update
  10. Prepara l'ambiente di sviluppo.

    Vai alla guida alla configurazione di Node.js

  11. Crea una funzione

    1. Crea una directory sul sistema locale per il codice della funzione:

      Linux o Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. Crea un file index.js nella directory helloworld con il seguente contenuto:

      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')}!`);
      });

      Questa funzione di esempio prende un nome fornito nella richiesta HTTP e restituisce un saluto oppure "Hello World!" se non viene fornito alcun nome.

    Specifica delle dipendenze

    Le dipendenze in Node.js vengono memorizzate in un file denominato package.json. Puoi creare questo file manualmente o con il comando npm.

    • Per creare il file di dipendenze package.json utilizzando npm, esegui questi comandi:

      npm init
      npm install c8 gaxios mocha sinon supertest wait-port --save-dev
      npm install @google-cloud/functions-framework escape-html
      
    • Se preferisci creare manualmente il file package.json, crea un file package.json nella directory helloworld con il seguente contenuto:

      {
        "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"
        }
      }
      

    esegui il deployment della funzione

    Per il deployment della funzione con un trigger HTTP, esegui questo comando nella directory helloworld:

    gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated
    

    Il flag --allow-unauthenticated consente di raggiungere la funzione senza autenticazione. Per richiedere l'autenticazione, ometti il flag.

    Testa la funzione

    1. Al termine del deployment della funzione, annota la proprietà httpsTrigger.url o cercala utilizzando il seguente comando:

      gcloud functions describe helloHttp
      

      Dovrebbe avere il seguente aspetto:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
    2. Accedi all'URL dal browser. Dovresti vedere il messaggio "Hello World!".

      Prova a inserire un nome nella richiesta HTTP, ad esempio utilizzando il seguente URL:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME

      Dovresti vedere il messaggio "Hello NAME!"

    Visualizza i log

    I log per Cloud Run Functions sono visualizzabili utilizzando Google Cloud CLI e nell'interfaccia utente di Cloud Logging.

    Utilizzare lo strumento a riga di comando

    Per visualizzare i log per la tua funzione con gcloud CLI, utilizza il comando logs read, seguito dal nome della funzione:

    gcloud functions logs read helloHttp

    L'output dovrebbe essere simile al seguente:

    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

    Utilizzare la dashboard Logging

    Puoi visualizzare i log per Cloud Run Functions anche dalla consoleGoogle Cloud .