Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Criar e implantar uma função HTTP do Cloud Run usando Ruby (1ª geração)
Este guia explica o processo de criação de uma função do Cloud Run usando o
ambiente de execução do Ruby. Há dois tipos de funções do Cloud Run:
Uma função HTTP, que você invoca a partir de solicitações HTTP padrão.
Uma função direcionada a eventos, que você usa para processar eventos da infraestrutura do
Cloud, como mensagens em um tópico do Pub/Sub ou alterações em um
bucket do Cloud Storage.
O exemplo mostra como criar uma função HTTP simples.
Antes de começar
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.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Crie um arquivo app.rb no diretório helloworld com o seguinte conteúdo:
require"functions_framework"require"cgi"require"json"FunctionsFramework.http"hello_http"do|request|# The request parameter is a Rack::Request object.# See https://www.rubydoc.info/gems/rack/Rack/Requestname=request.params["name"]||(request.body.rewind && JSON.parse(request.body.read)["name"]rescuenil)||"World"# 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 #{CGI.escape_htmlname}!"end
Esse exemplo de função recebe um nome fornecido na solicitação HTTP e retorna
uma saudação, ou "Hello World!", quando nenhum nome é fornecido.
Especificar as dependências
Dependências no Ruby são gerenciadas com o Bundler (em inglês) e expressas em um arquivo chamado
Gemfile.
Quando você implanta sua função, as funções do Cloud Run faz o download e instala
as dependências declaradas em Gemfile e Gemfile.lock usando bundler.
O Gemfile lista os pacotes obrigatórios para a função junto com
as restrições de versão opcionais. Para uma função do Cloud Run, um desses pacotes precisa ser o gem functions_framework.
Neste exercício, crie um arquivo chamado Gemfile no mesmo diretório que o
app.rb que contém o código da função, com o seguinte conteúdo:
Execute o seguinte comando para instalar o gem functions_framework e outras
dependências:
bundleinstall
Criar e testar localmente
Antes de implantar a função, é possível criá-la e testá-la localmente:
Execute o seguinte comando para usar o executável functions-framework-ruby para iniciar um servidor da Web local executando sua função hello_http:
bundleexecfunctions-framework-ruby--targethello_http# ...starts the web server in the foreground
Se a função for criada com sucesso, ela exibirá o URL que você pode visitar no
navegador da Web para ver a função em ação:
http://localhost:8080/. Você verá uma mensagem Hello World!.
Como alternativa, envie solicitações para essa função usando curl de outra
janela de terminal:
curllocalhost:8080# Output: Hello World!
Consulte também
Como testar funções na documentação do framework de funções do Ruby.
Implantar a função
Para implantar a função com um gatilho HTTP, execute o seguinte
comando no diretório helloworld:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-05 UTC."],[[["\u003cp\u003eThis guide details how to create and deploy an HTTP Cloud Run function using the Ruby runtime environment, enabling it to be invoked via standard HTTP requests.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves creating an \u003ccode\u003eapp.rb\u003c/code\u003e file with the function code, which, in this example, generates a personalized greeting based on a name provided in the HTTP request, defaulting to "Hello World!".\u003c/p\u003e\n"],["\u003cp\u003eDependencies for the Ruby Cloud Run function are managed using Bundler and a \u003ccode\u003eGemfile\u003c/code\u003e, where \u003ccode\u003efunctions_framework\u003c/code\u003e gem is required, and they are installed during the deployment.\u003c/p\u003e\n"],["\u003cp\u003eBefore deploying, the function can be built and tested locally using \u003ccode\u003efunctions-framework-ruby\u003c/code\u003e, allowing verification of its behavior before it goes live.\u003c/p\u003e\n"],["\u003cp\u003eThe function is deployed via the \u003ccode\u003egcloud functions deploy\u003c/code\u003e command, which can include the \u003ccode\u003e--allow-unauthenticated\u003c/code\u003e flag to permit access without requiring prior authentication.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Create and deploy an HTTP Cloud Run function by using Ruby\n\nCreate and deploy an HTTP Cloud Run function by using Ruby (1st gen)\n====================================================================\n\nThis guide takes you through the process of writing a Cloud Run function\nusing the Ruby runtime. There are two types of Cloud Run functions:\n\n- An HTTP function, which you invoke from standard HTTP requests.\n- An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Pub/Sub topic, or changes in a Cloud Storage bucket.\n\nThe sample shows how to create a simple HTTP function.\n| **Learn more** : For more details, read about [HTTP functions](/functions/1stgendocs/writing/write-http-functions) and [event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions).\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n1. [Install and initialize the gcloud CLI](/sdk/docs).\n2. Update and install `gcloud` components: \n\n ```bash\n gcloud components update\n ```\n| **Note** : Need a command prompt? You can use [Cloud Shell](https://console.cloud.google.com/?cloudshell=true). Cloud Shell is a command line environment that already includes the Google Cloud CLI, so you don't need to install it. The Google Cloud CLI also comes preinstalled on Compute Engine Virtual Machines.\n3. Prepare your development environment.\n [Go to the Ruby setup guide](/ruby/docs/setup)\n\nCreate a function\n-----------------\n\n1. Create a directory on your local system for the function code:\n\n ### Linux or Mac OS X\n\n mkdir ~/helloworld\n cd ~/helloworld\n\n ### Windows\n\n mkdir %HOMEPATH%\\helloworld\n cd %HOMEPATH%\\helloworld\n\n2. Create an `app.rb` file in the `helloworld` directory with the\n following contents:\n\n require \"functions_framework\"\n require \"cgi\"\n require \"json\"\n\n FunctionsFramework.http \"hello_http\" do |request|\n # The request parameter is a Rack::Request object.\n # See https://www.rubydoc.info/gems/rack/Rack/Request\n name = request.params[\"name\"] ||\n (request.body.rewind && JSON.parse(request.body.read)[\"name\"] rescue nil) ||\n \"World\"\n # Return the response body as a string.\n # You can also return a Rack::Response object, a Rack response array, or\n # a hash which will be JSON-encoded into a response.\n \"Hello #{CGI.escape_html name}!\"\n end\n\n This example function takes a name supplied in the HTTP request and returns\n a greeting, or \"Hello World!\" when no name is supplied.\n | **Note:** Cloud Run functions looks for deployable functions in `app.rb` by default. Use the [`--source`](/sdk/gcloud/reference/functions/deploy#--source) flag when [deploying your function using `gcloud`](#deploy_the_function) to specify a different directory containing an `app.rb` file.\n\nSpecify dependencies\n--------------------\n\nDependencies in Ruby are managed with [bundler](https://bundler.io) and expressed in a file called\n`Gemfile`.\n\nWhen you deploy your function, Cloud Run functions downloads and installs the\ndependencies declared in the `Gemfile` and `Gemfile.lock` using `bundler`.\n\nThe `Gemfile` lists the packages required by your function, along with any\noptional version constraints. For a Cloud Run function, one of these\npackages must be the `functions_framework` gem.\n\nFor this exercise, create a file named `Gemfile` in the same directory as the\n`app.rb` file that contains your function code, with the following contents: \n\n```\nsource \"https://rubygems.org\"\n\ngem \"functions_framework\", \"~\u003e 0.7\"\n```\n\nRun the following command to install the `functions_framework` gem and other\ndependencies: \n\n bundle install\n\n| **Learn more** : For more details, read about [specifying dependencies](/functions/1stgendocs/writing/specifying-dependencies-ruby).\n\nBuild and test locally\n----------------------\n\nBefore deploying the function, you can build and test it locally.\nRun the following command to use the `functions-framework-ruby` executable to\nstart a local web server running your `hello_http` function: \n\n bundle exec functions-framework-ruby --target hello_http\n # ...starts the web server in the foreground\n\nIf the function builds successfully, it displays the URL you can visit in your\nweb browser to see the function in action:\n`http://localhost:8080/`. You should see a `Hello World!` message.\n\nAlternatively, you can send requests to this function using `curl` from another\nterminal window: \n\n curl localhost:8080\n # Output: Hello World!\n\nSee [Testing Functions](https://github.com/GoogleCloudPlatform/functions-framework-ruby#documentation)\nin the Ruby Functions Framework documentation.\n\nDeploy the function\n-------------------\n\nTo deploy the function with an HTTP trigger, run the following\ncommand in the `helloworld` directory: \n\n gcloud functions deploy hello_http --no-gen2 --runtime ruby33 --trigger-http --allow-unauthenticated\n\nThe `--allow-unauthenticated` flag lets you reach the function\n[without authentication](/functions/1stgendocs/securing/managing-access-iam#allowing_unauthenticated_http_function_invocation).\nTo require\n[authentication](/functions/1stgendocs/securing/authenticating#developers), omit the\nflag.\n| **Learn more** : For more details, read about [deploying Cloud Run functions](/functions/1stgendocs/deploy#basics).\n\nTest the deployed function\n--------------------------\n\n1. When the function finishes deploying, take note of the `httpsTrigger.url`\n property or find it using the following command:\n\n gcloud functions describe hello_http\n\n It should look like this: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http\n ```\n2. Visit this URL in your browser. You should see a \"Hello World!\" message.\n\n Try passing a name in the HTTP request, for example by using the following\n URL: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME\n ```\n\n You should see the message \"Hello \u003cvar translate=\"no\"\u003eNAME\u003c/var\u003e!\"\n\nView logs\n---------\n\nYou can view Cloud Run functions logs in the Cloud Logging UI or through the\nGoogle Cloud CLI.\n\n### View logs with the command-line tool\n\nTo view logs for your function with the gcloud CLI, use the\n[`logs read`](/sdk/gcloud/reference/functions/logs/read) command, followed by\nthe name of the function: \n\n```bash\ngcloud functions logs read hello_http\n```\n\nThe output should resemble the following: \n\n```bash\nLEVEL NAME EXECUTION_ID TIME_UTC LOG\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200\n```\n| **Note:** There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.\n\n### View logs in the Logging dashboard\n\nYou can also view logs for Cloud Run functions from the\n[Google Cloud console](https://console.cloud.google.com/project/_/logs?service=cloudfunctions.googleapis.com).\n| **Learn more** : For more details, read about [writing, viewing, and responding to logs](/functions/1stgendocs/monitoring/logging)."]]