Tutorial su HTTP


Questo semplice tutorial mostra come scrivere, eseguire il deployment e attivare una funzione Cloud Run HTTP.

Obiettivi

Costi

In questo documento vengono utilizzati i seguenti componenti fatturabili di Google Cloud:

  • Cloud Run functions

Per generare una stima dei costi in base all'utilizzo previsto, utilizza il calcolatore prezzi.

I nuovi utenti di Google Cloud potrebbero avere diritto a una prova senza costi.

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.

    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. Install the Google Cloud CLI.

  6. Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

  7. Per inizializzare gcloud CLI, esegui questo comando:

    gcloud init
  8. 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

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

  10. 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

  11. Install the Google Cloud CLI.

  12. Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

  13. Per inizializzare gcloud CLI, esegui questo comando:

    gcloud init
  14. Se hai già installato gcloud CLI, aggiornala eseguendo il seguente comando:

    gcloud components update
  15. Prepara l'ambiente di sviluppo.
  16. Preparazione della richiesta

    1. Clona il repository dell'app di esempio sulla tua macchina locale:

      Node.js

      git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

      In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

      Python

      git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

      In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

      Vai

      git clone https://github.com/GoogleCloudPlatform/golang-samples.git

      In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

      Java

      git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

      In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

      Ruby

      git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

      In alternativa, puoi scaricare il campione come file ZIP ed estrarlo.

    2. Passa alla directory che contiene il codice campione delle funzioni Cloud Run:

      Node.js

      cd nodejs-docs-samples/functions/helloworld/

      Python

      cd python-docs-samples/functions/helloworld/

      Vai

      cd golang-samples/functions/helloworld/

      Java

      cd java-docs-samples/functions/helloworld/helloworld/

      Ruby

      cd ruby-docs-samples/functions/helloworld/

    3. Dai un'occhiata al codice campione:

      Node.js

      const functions = require('@google-cloud/functions-framework');
      
      // Register an HTTP function with the Functions Framework that will be executed
      // when you make an HTTP request to the deployed function's endpoint.
      functions.http('helloGET', (req, res) => {
        res.send('Hello World!');
      });

      Python

      import functions_framework
      
      @functions_framework.http
      def hello_get(request):
          """HTTP Cloud Function.
          Args:
              request (flask.Request): The request object.
              <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
          Returns:
              The response text, or any set of values that can be turned into a
              Response object using `make_response`
              <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
          Note:
              For more information on how Flask integrates with Cloud
              Functions, see the `Writing HTTP functions` page.
              <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
          """
          return "Hello World!"
      
      

      Go

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"fmt"
      	"net/http"
      )
      
      // HelloGet is an HTTP Cloud Function.
      func HelloGet(w http.ResponseWriter, r *http.Request) {
      	fmt.Fprint(w, "Hello, World!")
      }
      

      Java

      
      package functions;
      
      import com.google.cloud.functions.HttpFunction;
      import com.google.cloud.functions.HttpRequest;
      import com.google.cloud.functions.HttpResponse;
      import java.io.BufferedWriter;
      import java.io.IOException;
      
      public class HelloWorld implements HttpFunction {
        // Simple function to return "Hello World"
        @Override
        public void service(HttpRequest request, HttpResponse response)
            throws IOException {
          BufferedWriter writer = response.getWriter();
          writer.write("Hello World!");
        }
      }

      Ruby

      require "functions_framework"
      
      FunctionsFramework.http "hello_get" do |_request|
        # The request parameter is a Rack::Request object.
        # See https://www.rubydoc.info/gems/rack/Rack/Request
      
        # Return the response body as a string.
        # You can also return a Rack::Response object, a Rack response array, or
        # a hash which will be JSON-encoded into a response.
        "Hello World!"
      end

    Deployment della funzione

    Per il deployment della funzione con un trigger HTTP, esegui questo comando nella directory che contiene il codice campione (o, nel caso di Java, il file pom.xml):

    Node.js

    gcloud functions deploy helloGET \
    --runtime nodejs20 --trigger-http

    Utilizza il flag --runtime per specificare l'ID runtime di una versione di Node.js supportata per eseguire la funzione.

    Python

    gcloud functions deploy hello_get \
    --runtime python312 --trigger-http

    Utilizza il flag --runtime per specificare l'ID runtime di una versione di Python supportata per eseguire la funzione.

    Vai

    gcloud functions deploy HelloGet \
    --runtime go121 --trigger-http

    Utilizza il flag --runtime per specificare l'ID runtime di una versione di Go supportata per eseguire la funzione.

    Java

    gcloud functions deploy java-http-function \
    --entry-point functions.HelloWorld \
    --runtime java17 \
    --memory 512MB --trigger-http

    Utilizza il flag --runtime per specificare l'ID runtime di una versione Java supportata per eseguire la funzione.

    Ruby

    gcloud functions deploy hello_get --runtime ruby33 --trigger-http

    Utilizza il flag --runtime per specificare l'ID runtime di una versione di Ruby supportata per eseguire la funzione.

    Se vuoi, puoi utilizzare il flag --allow-unauthenticated per raggiungere la funzione senza autenticazione. Questa impostazione è utile per i test, ma non è consigliabile utilizzarla in produzione, a meno che tu non stia creando un'API o un sito web pubblici. Inoltre, potrebbe non funzionare per te, a seconda delle impostazioni dei criteri aziendali. Consulta Autenticazione per le chiamate per informazioni dettagliate su come richiamare una funzione che richiede l'autenticazione.

    Attivazione della funzione

    Per effettuare una richiesta HTTP alla tua funzione, esegui questo comando:

    Node.js

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/helloGET" 

    Python

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

    Vai

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/HelloGet" 

    Java

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/java-http-function" 

    Ruby

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

    dove

    • REGION è la regione in cui viene eseguito il deployment della funzione. Queste informazioni sono visibili nel terminale al termine del deployment della funzione.
    • PROJECT_ID è il tuo ID progetto Cloud. Questo messaggio è visibile nel terminale al termine del deployment della funzione.

    Puoi anche visitare l'endpoint della funzione di cui è stato eseguito il deployment nel browser per visualizzare il messaggio "Hello World!".

    Esegui la pulizia

    Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo tutorial, elimina il progetto che contiene le risorse oppure mantieni il progetto ed elimina le singole risorse.

    Elimina il progetto

    Il modo più semplice per eliminare la fatturazione è eliminare il progetto creato per il tutorial.

    Per eliminare il progetto:

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    Eliminazione della funzione

    L'eliminazione delle funzioni Cloud Run non rimuove le risorse archiviate in Cloud Storage.

    Per eliminare la funzione Cloud Run che hai creato in questo tutorial, esegui questo comando:

    Node.js

    gcloud functions delete helloGET 

    Python

    gcloud functions delete hello_get 

    Vai

    gcloud functions delete HelloGet 

    Java

    gcloud functions delete java-http-function 

    Ruby

    gcloud functions delete hello_get 

    Puoi anche eliminare le funzioni Cloud Run dalla consoleGoogle Cloud .