Instructivo HTTP


En este instructivo sencillo, se muestra cómo escribir, implementar y activar una Cloud Run Function HTTP.

Objetivos

Costos

En este documento, usarás los siguientes componentes facturables de Google Cloud:

  • Cloud Run functions

Para generar una estimación de costos en función del uso previsto, usa la calculadora de precios.

Es posible que los usuarios de Google Cloud nuevos cumplan con los requisitos para acceder a una prueba gratuita.

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

  6. Si usas un proveedor de identidad externo (IdP), primero debes acceder a gcloud CLI con tu identidad federada.

  7. Para inicializar gcloud CLI, ejecuta el siguiente 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. Si usas un proveedor de identidad externo (IdP), primero debes acceder a gcloud CLI con tu identidad federada.

  13. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init
  14. Si ya tienes instalado gcloud CLI, ejecuta el siguiente comando para actualizarla:

    gcloud components update
  15. Prepara tu entorno de desarrollo.
  16. Prepara la aplicación

    1. Clona el repositorio de la app de muestra en tu máquina local:

      Node.js

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

      De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

      Python

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

      De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

      Go

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

      De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

      Java

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

      De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

      Ruby

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

      De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    2. Ve al directorio que contiene el código de muestra de funciones de Cloud Run:

      Node.js

      cd nodejs-docs-samples/functions/helloworld/

      Python

      cd python-docs-samples/functions/helloworld/

      Go

      cd golang-samples/functions/helloworld/

      Java

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

      Ruby

      cd ruby-docs-samples/functions/helloworld/

    3. Ve el código de muestra:

      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

    Implementa la función

    Para implementar la función con un activador de HTTP, ejecuta el siguiente comando en el directorio que contiene el código de muestra (o, en el caso de Java, el archivo pom.xml):

    Node.js

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

    Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión compatible de Node.js para ejecutar la función.

    Python

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

    Usa la marca --runtime para especificar el ID de entorno de ejecución de una versión de Python compatible para ejecutar la función.

    Go

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

    Usa la marca --runtime para especificar el ID de entorno de ejecución de una versión de Go compatible para ejecutar tu función.

    Java

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

    Usa la marca --runtime para especificar el ID del entorno de ejecución de una versión de Java compatible para ejecutar tu función.

    Ruby

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

    Usa la marca --runtime para especificar el ID de entorno de ejecución de una versión de Ruby compatible para ejecutar tu función.

    De forma opcional, puedes usar la marca --allow-unauthenticated para acceder a la función sin autenticación. Esto es útil para realizar pruebas, pero no se recomienda usar esta configuración en producción, a menos que crees una API pública o un sitio web. Además, es posible que no funcione en tu caso, según la configuración de tu política corporativa. Consulta Autentica para la invocación para obtener detalles sobre cómo invocar una función que requiere autenticación.

    Activa la función

    Para hacer una solicitud HTTP a tu función, ejecuta el siguiente comando:

    Node.js

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

    Python

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

    Go

    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" 

    donde

    • REGION es la región en la que se implementa tu función. Esta se puede ver en tu terminal cuando la función termina de implementarse.
    • PROJECT_ID es el ID del proyecto de Cloud. Esta se puede ver en tu terminal cuando la función termina de implementarse.

    También puedes visitar el extremo de la función implementada en tu navegador para ver el mensaje “Hello World!”.

    Limpia

    Para evitar que se apliquen cargos a tu cuenta de Google Cloud por los recursos usados en este instructivo, borra el proyecto que contiene los recursos o conserva el proyecto y borra los recursos individuales.

    Borra el proyecto

    La manera más fácil de eliminar la facturación es borrar el proyecto que creaste para el instructivo.

    Para borrar el proyecto, sigue estos pasos:

    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.

    Borra la función

    Borrar las funciones de Cloud Run no quita ningún recurso almacenado en Cloud Storage.

    Para borrar la función de Cloud Run que creaste en este instructivo, ejecuta el siguiente comando:

    Node.js

    gcloud functions delete helloGET 

    Python

    gcloud functions delete hello_get 

    Go

    gcloud functions delete HelloGet 

    Java

    gcloud functions delete java-http-function 

    Ruby

    gcloud functions delete hello_get 

    También puedes borrar funciones de Cloud Run en la consola deGoogle Cloud .