Se stai creando una nuova funzione, consulta la guida rapida della console su Cloud Run. I contenuti di questa pagina si applicano solo alle funzioni legacy esistenti create con l'API Cloud Functions v1.
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Crea ed esegui il deployment di una funzione Cloud Run HTTP utilizzando Ruby (1ª generazione.)
Questa guida ti illustra la procedura di scrittura di una funzione Cloud Run
utilizzando il runtime Ruby. 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
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.
Crea un file app.rb nella directory helloworld con il seguente contenuto:
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
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
Le dipendenze in Ruby vengono gestite con bundler ed espresse in un file denominato
Gemfile.
Quando esegui il deployment della funzione, Cloud Run Functions scarica e installa le dipendenze dichiarate in Gemfile e Gemfile.lock utilizzando bundler.
Il file Gemfile elenca i pacchetti richiesti dalla tua funzione, insieme a eventuali vincoli di versione facoltativi. Per una funzione Cloud Run, uno di questi
pacchetti deve essere la gemma functions_framework.
Per questo esercizio, crea un file denominato Gemfile nella stessa directory del file app.rb che contiene il codice della funzione, con il seguente contenuto:
Esegui questo comando per installare il gem functions_framework e altre
dipendenze:
bundleinstall
Creare build e testare in locale
Prima di eseguire il deployment della funzione, puoi compilarla e testarla localmente.
Esegui questo comando per utilizzare l'eseguibile functions-framework-ruby per
avviare un server web locale che esegue la funzione hello_http:
bundleexecfunctions-framework-ruby--targethello_http# ...starts the web server in the foreground
Se la funzione viene creata correttamente, viene visualizzato l'URL che puoi visitare nel browser web per vedere la funzione in azione:
http://localhost:8080/. Dovresti visualizzare un messaggio Hello World!.
In alternativa, puoi inviare richieste a questa funzione utilizzando curl da un'altra finestra del terminale:
curllocalhost:8080# Output: Hello World!
Consulta la sezione Test delle funzioni
nella documentazione di Functions Framework per Ruby.
esegui il deployment della funzione
Per il deployment della funzione con un trigger HTTP, esegui questo comando nella directory helloworld:
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-10 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)."]]