Crea e implementa una Cloud Run Function HTTP con Go (1ª gen.)

En esta guía, se explica el proceso para escribir una función de Cloud Run con el entorno de ejecución de Go. Existen dos tipos de funciones de Cloud Run:

  • Una función de HTTP que se invoca a partir de solicitudes HTTP estándar.
  • La otra es una función controlada por eventos que se usa para manejar los eventos de la infraestructura de tu nube, como mensajes en un tema de Cloud Pub/Sub o cambios en un bucket de Cloud Storage.

En el ejemplo, se muestra cómo crear una función de HTTP simple.

Antes de comenzar

  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. Instala y actualiza componentes de gcloud:
    gcloud components update
  10. Prepara tu entorno de desarrollo.

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

  11. Crea una función

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

      Linux o MacOS 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 muestra un saludo o “Hello, World!” cuando 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 necesitas declarar ninguna dependencia más allá de solo importar los paquetes.

    Para las funciones que requieren dependencias fuera de la biblioteca estándar, debes proporcionar las dependencias a través de un archivo go.mod o un directorio vendor. Para obtener más información, lee Especificar dependencias en Go.

    Implementa la función

    Para implementar la función con un activador de HTTP, ejecuta el siguiente comando en el directorio helloworld y especifica go113 o go111 como el valor de la marca --runtime, según la versión que uses:

    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 solicitar la autenticación, omite la marca.

    Prueba la función

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

      gcloud functions describe HelloHTTP
      

      Se verá de la siguiente manera:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP
    2. Visita esta URL en tu navegador o usa cURL mediante la ejecución del siguiente comando:

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

      Deberías ver el mensaje “Hello, World!”. Intenta pasar un nombre en la solicitud HTTP mediante la ejecución del siguiente comando:

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

      Deberías ver el mensaje “Hello, NAME!”

    Ver registros

    Los registros de Cloud Run Functions pueden verse con Google Cloud CLI y en la IU de Cloud Logging.

    Usa la herramienta de línea de comandos

    Para visualizar 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

    El resultado debe parecerse al 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

    Usa el panel de Logging

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