Crea ed esegui il deployment di una funzione Cloud Run HTTP utilizzando Go (1ª generazione.)

Questa guida ti accompagna nella procedura di scrittura di una funzione Cloud Run utilizzando il runtime Go. 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. Verify 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. Verify 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 Go

  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 denominato hello_http.go nella directory helloworld con il seguente contenuto:

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"encoding/json"
      	"fmt"
      	"html"
      	"net/http"
      
      	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
      )
      
      func init() {
      	functions.HTTP("HelloHTTP", HelloHTTP)
      }
      
      // HelloHTTP is an HTTP Cloud Function with a request parameter.
      func HelloHTTP(w http.ResponseWriter, r *http.Request) {
      	var d struct {
      		Name string `json:"name"`
      	}
      	if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
      		fmt.Fprint(w, "Hello, World!")
      		return
      	}
      	if d.Name == "" {
      		fmt.Fprint(w, "Hello, World!")
      		return
      	}
      	fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
      }
      

      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

    Questa funzione di esempio utilizza solo pacchetti della libreria standard Go, quindi non devi dichiarare dipendenze oltre a importare i pacchetti.

    Per le funzioni che richiedono dipendenze esterne alla libreria standard, devi fornire le dipendenze tramite un file go.mod o una directory vendor. Per maggiori dettagli, leggi Specifica delle dipendenze in Go.

    esegui il deployment della funzione

    Per il deployment della funzione con un trigger HTTP, esegui questo comando nella directory helloworld, specificando go113 o go111 come valore per il flag --runtime, a seconda della versione che utilizzi:

    gcloud functions deploy HelloHTTP --no-gen2 --runtime go121 --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. Visita questo URL nel browser o utilizza cURL eseguendo il comando:

      curl https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP

      Dovresti vedere il messaggio "Hello, World!". Prova a inserire un nome nella richiesta HTTP eseguendo questo comando:

      curl -X POST https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP -H "Content-Type:application/json"  -d '{"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  buv9ej2k1a7r  2019-09-20 13:23:18.910  Function execution started
    D      HelloHTTP  buv9ej2k1a7r  2019-09-20 13:23:18.913  Function execution took 4 ms, finished with status code: 200

    Utilizzare la dashboard Logging

    Puoi visualizzare i log per le funzioni Cloud Run anche dalla consoleGoogle Cloud .