Crear y desplegar una función de Cloud Run activada por HTTP con Go (1.ª gen.)

En esta guía se explica cómo escribir una función de Cloud Run con el entorno de ejecución de Go. Hay dos tipos de funciones de Cloud Run:

  • Una función HTTP, que se invoca desde solicitudes HTTP estándar.
  • Una función basada en eventos que se usa para gestionar eventos de tu infraestructura de Cloud, como mensajes de un tema de Pub/Sub o cambios en un segmento de Cloud Storage.

En el ejemplo se muestra cómo crear una función HTTP sencilla.

Antes de empezar

  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. Instala e inicializa gcloud CLI.
  9. Actualiza e instala los componentes de gcloud:
    gcloud components update
  10. Prepara tu entorno de desarrollo.

    Ve a la guía de configuración de Go

  11. Crear una función

    1. Crea un directorio en tu sistema local para el código de la función:

      Linux o Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. Crea un archivo llamado hello_http.go en el directorio helloworld con el siguiente contenido:

      
      // 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))
      }
      

      Esta función de ejemplo toma un nombre proporcionado en la solicitud HTTP y devuelve un saludo o "Hello, World!" si no se proporciona ningún nombre.

    Especificar dependencias

    Esta función de ejemplo solo usa paquetes de la biblioteca estándar de Go, por lo que no tienes que declarar ninguna dependencia más allá de importar los paquetes.

    En el caso de las funciones que requieren dependencias fuera de la biblioteca estándar, debe proporcionar las dependencias a través de un archivo go.mod o un directorio vendor. Para obtener más información, consulta el artículo Especificar dependencias en Go.

    Desplegar la función

    Para desplegar la función con un activador HTTP, ejecuta el siguiente comando en el directorio helloworld y especifica go113 o go111 como valor de la marca --runtime, en función de la versión que estés usando:

    gcloud functions deploy HelloHTTP --no-gen2 --runtime go121 --trigger-http --allow-unauthenticated

    La marca --allow-unauthenticated te permite acceder a la función sin autenticación. Para requerir autenticación, omite la marca.

    Probar función

    1. Cuando la función termine de implementarse, anota la propiedad httpsTrigger.url o búscala con el siguiente comando:

      gcloud functions describe HelloHTTP
      

      Debería tener este aspecto:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP
    2. Visita esta URL en tu navegador o usa cURL ejecutando el comando:

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

      Debería aparecer el mensaje "Hello, World!". Prueba a enviar un nombre en la solicitud HTTP ejecutando el siguiente comando:

      curl -X POST https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP -H "Content-Type:application/json"  -d '{"name":"NAME"}'

      Debería aparecer el mensaje "Hola, NAME".

    Ver registros

    Los registros de las funciones de Cloud Run se pueden ver con la CLI de Google Cloud y en la interfaz de usuario de Cloud Logging.

    Usar la herramienta de línea de comandos

    Para ver los registros de tu función con gcloud CLI, usa el comando logs read, seguido del nombre de la función:

    gcloud functions logs read HelloHTTP

    La salida debería ser similar a la siguiente:

    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

    Usar el panel de control de Logging

    También puedes ver los registros de las funciones de Cloud Run desde la Google Cloud consola.