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
  • Cloud Build
  • Artifact Registry

For details, see Cloud Run functions pricing.

Per generare una stima dei costi basata sull'utilizzo previsto, utilizza il Calcolatore prezzi. I nuovi utenti di Google Cloud potrebbero essere idonei per una prova gratuita.

Prima di iniziare

  1. Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  4. Enable the Cloud Functions, Cloud Build, and Artifact Registry APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Assicurati che la fatturazione sia attivata per il tuo progetto Google Cloud.

  9. Enable the Cloud Functions, Cloud Build, and Artifact Registry APIs.

    Enable the APIs

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. Se hai già installato gcloud CLI, aggiornalo eseguendo il seguente comando:

    gcloud components update
  13. Prepara l'ambiente di sviluppo.

Preparazione dell'applicazione

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

    Node.js

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Python

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Vai

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Java

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    C#

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    Ruby

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

    In alternativa, puoi scarica l'esempio . come file ZIP ed estrarlo.

    PHP

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

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

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

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Vai

    cd golang-samples/functions/functionsv2/helloworld/

    Java

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

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloWorld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/get/

    PHP

    cd php-docs-samples/functions/helloworld_get/

  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!"
    
    

    Vai

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    )
    
    func init() {
    	functions.HTTP("HelloGet", helloGet)
    }
    
    // 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!");
      }
    }

    C#

    using Google.Cloud.Functions.Framework;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace HelloWorld;
    
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello World!", context.RequestAborted);
        }
    }

    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

    PHP

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

Deployment della funzione

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

Node.js

gcloud functions deploy nodejs-http-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGET \
--trigger-http

Utilizza la --runtime per specificare l'ID runtime di un versione Node.js supportata per l'esecuzione la tua funzione.

Python

gcloud functions deploy python-http-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_get \
--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 go-http-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloGet \
--trigger-http

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

Java

gcloud functions deploy java-http-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloWorld \
--memory=512MB \
--trigger-http

Utilizza la --runtime per specificare l'ID runtime di un versione Java supportata per l'esecuzione la tua funzione.

C#

gcloud functions deploy csharp-http-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloWorld.Function \
--trigger-http

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

Ruby

gcloud functions deploy ruby-http-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_get \
-
-trigger-http

Utilizza la --runtime per specificare l'ID runtime di un versione Ruby supportata per l'esecuzione la tua funzione.

PHP

gcloud functions deploy php-http-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGet \
-
-trigger-http

Utilizza la --runtime per specificare l'ID runtime di un versione PHP supportata per l'esecuzione la tua funzione.

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

Attivazione della funzione

  1. Identifica l'URL della funzione di cui hai eseguito il deployment.

  2. Accedi all'URL dal browser. Dovresti vedere un 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 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 di Cloud Run non rimuove le risorse archiviate in Cloud Storage.

Per eliminare la funzione creata in questo tutorial: esegui questo comando:

Node.js

gcloud functions delete nodejs-http-function --gen2 --region REGION 

Python

gcloud functions delete python-http-function --gen2 --region REGION 

Vai

gcloud functions delete go-http-function --gen2 --region REGION 

Java

gcloud functions delete java-http-function --gen2 --region REGION 

C#

gcloud functions delete csharp-http-function --gen2 --region REGION 

Ruby

gcloud functions delete ruby-http-function --gen2 --region REGION 

PHP

gcloud functions delete php-http-function --gen2 --region REGION 

Puoi eliminare le funzioni Cloud Run anche dalla console Google Cloud.