Si vous créez une fonction, consultez le guide de démarrage rapide de la console sur Cloud Run. Le contenu de cette page ne s'applique qu'aux anciennes fonctions existantes créées avec l'API Cloud Functions v1.
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Créer et déployer une fonction Cloud Run HTTP à l'aide de Go (1re génération)
Ce guide vous accompagne tout au long du processus d'écriture d'une fonction Cloud Run à l'aide de l'environnement d'exécution Go. Il existe deux types de fonctions Cloud Run :
Les fonctions HTTP, que vous appelez à partir des requêtes HTTP standards.
Les fonctions déclenchées par des événements, qui vous permettent de gérer les événements depuis votre infrastructure cloud tels que les messages sur un sujet Pub/Sub ou les modifications apportées à un bucket Cloud Storage.
L'exemple montre comment créer une fonction HTTP simple.
Avant de commencer
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.
Créez un répertoire sur votre système local pour le code de fonction :
Linux ou Mac OS X
mkdir ~/helloworld
cd ~/helloworld
Windows
mkdir %HOMEPATH%\helloworld
cd %HOMEPATH%\helloworld
Créez un fichier hello_http.go dans le répertoire helloworld avec le contenu suivant :
// Package helloworld provides a set of Cloud Functions samples.packagehelloworldimport("encoding/json""fmt""html""net/http""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit(){functions.HTTP("HelloHTTP",HelloHTTP)}// HelloHTTP is an HTTP Cloud Function with a request parameter.funcHelloHTTP(whttp.ResponseWriter,r*http.Request){vardstruct{Namestring`json:"name"`}iferr:=json.NewDecoder(r.Body).Decode(&d);err!=nil{fmt.Fprint(w,"Hello, World!")return}ifd.Name==""{fmt.Fprint(w,"Hello, World!")return}fmt.Fprintf(w,"Hello, %s!",html.EscapeString(d.Name))}
Cet exemple de fonction utilise un nom fourni dans la requête HTTP et renvoie un message d'accueil. Lorsqu'aucun nom n'est fourni, il renvoie le message "Hello World!".
Spécifier des dépendances
Cet exemple de fonction n'utilise que des packages de bibliothèque standard Go. En dehors de l'importation des packages, vous n'avez donc pas besoin de déclarer les dépendances.
Pour les fonctions ayant des dépendances en dehors de la bibliothèque standard, vous devez fournir les dépendances via un fichier go.mod ou un répertoire vendor. Pour en savoir plus, consultez la page Spécifier des dépendances en Go.
Déployer la fonction
Pour déployer la fonction avec un déclencheur HTTP, exécutez la commande suivante dans le répertoire helloworld, en spécifiant go113 ou go111 (suivant la version que vous utilisez) comme valeur pour l'option --runtime :
Vous pouvez également consulter les journaux Cloud Run Functions depuis la consoleGoogle Cloud .
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/05 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/05 (UTC)."],[[["\u003cp\u003eThis guide explains how to create and deploy an HTTP Cloud Run function using the Go programming language.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves setting up your development environment, including installing the gcloud CLI and preparing the Go environment.\u003c/p\u003e\n"],["\u003cp\u003eYou'll create a simple HTTP function in a \u003ccode\u003ehello_http.go\u003c/code\u003e file, which takes an optional name parameter in the HTTP request and returns a greeting.\u003c/p\u003e\n"],["\u003cp\u003eDeploy the function using the \u003ccode\u003egcloud functions deploy\u003c/code\u003e command with the appropriate runtime and trigger settings, and it can be set to be accessible without authentication.\u003c/p\u003e\n"],["\u003cp\u003eYou can test the deployed function by visiting its URL in a browser or using \u003ccode\u003ecurl\u003c/code\u003e, and you can view function logs using the gcloud CLI or the Cloud Logging UI.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Create and deploy an HTTP Cloud Run function by using Go\n\nCreate and deploy an HTTP Cloud Run function\nby using Go (1st gen)\n==================================================================\n\nThis guide takes you through the process of writing a Cloud Run function\nusing the Go 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/1stgendocs/create-deploy-http-go-1st-gen)\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/1stgendocs/create-deploy-http-go-1st-gen)\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 the [Google Cloud\n| Shell](https://console.cloud.google.com/?cloudshell=true). The Google 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 Google Compute Engine Virtual Machines.\n3. Prepare your development environment.\n [Go to the Go setup guide](/go/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 a file called `hello_http.go` in the `helloworld`\n directory with the following contents:\n\n\n // Package helloworld provides a set of Cloud Functions samples.\n package helloworld\n\n import (\n \t\"encoding/json\"\n \t\"fmt\"\n \t\"html\"\n \t\"net/http\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n func init() {\n \tfunctions.HTTP(\"HelloHTTP\", HelloHTTP)\n }\n\n // HelloHTTP is an HTTP Cloud Function with a request parameter.\n func HelloHTTP(w http.ResponseWriter, r *http.Request) {\n \tvar d struct {\n \t\tName string `json:\"name\"`\n \t}\n \tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n \t\tfmt.Fprint(w, \"Hello, World!\")\n \t\treturn\n \t}\n \tif d.Name == \"\" {\n \t\tfmt.Fprint(w, \"Hello, World!\")\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"Hello, %s!\", html.EscapeString(d.Name))\n }\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\nSpecify dependencies\n--------------------\n\nThis example function only uses Go standard library packages, so you don't need\nto declare any dependencies beyond just importing the packages.\n\nFor functions that require dependencies outside of the standard library,\nyou must provide the dependencies via either a `go.mod` file or a `vendor`\ndirectory. For more details, read\n[Specifying dependencies in Go](/functions/1stgendocs/writing/specifying-dependencies-go).\n\nDeploy the function\n-------------------\n\nTo deploy the function with an HTTP trigger, run the following\ncommand in the `helloworld` directory, specifying either `go113` or\n`go111` as the value for the `--runtime` flag, depending on which version you\nare using: \n\n```sh\ngcloud functions deploy HelloHTTP --no-gen2 --runtime go121 --trigger-http --allow-unauthenticated\n```\n| **Note:** Cloud Run functions looks for deployable functions in your terminal's current directory by default. Use the [`--source`](/sdk/gcloud/reference/functions/deploy#--source) flag when [deploying your function via `gcloud`](#deploying_the_function) to specify a different function source directory.\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 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 HelloHTTP\n\n It should look like this: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP\n ```\n2. Visit this URL in your browser, or use cURL by running the command:\n\n ```sh\n curl https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP\n ```\n\n You should see a \"Hello, World!\" message. Try passing a name\n in the HTTP request by running the following command: \n\n ```sh\n curl -X POST https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloHTTP -H \"Content-Type:application/json\" -d '{\"name\":\"NAME\"}'\n ```\n\n You should see the message \"Hello, \u003cvar translate=\"no\"\u003eNAME\u003c/var\u003e!\"\n\nView logs\n---------\n\nLogs for Cloud Run functions are viewable using the Google Cloud CLI, and in the\nCloud Logging UI.\n\n### Use 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 HelloHTTP\n```\n\nThe output should resemble the following: \n\n```bash\nLEVEL NAME EXECUTION_ID TIME_UTC LOG\nD HelloHTTP buv9ej2k1a7r 2019-09-20 13:23:18.910 Function execution started\nD HelloHTTP buv9ej2k1a7r 2019-09-20 13:23:18.913 Function execution took 4 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### Use 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)."]]