Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Créer un service Web
Cette page explique comment créer un service Web dans la VM à l'aide du framework Web Gin, écrit en Golang. Vous pouvez choisir de créer le service Web dans n'importe quel autre framework.
Pour télécharger le package Go dans la VM, exécutez la commande suivante dans la VM :
wgethttps://go.dev/dl/go1.22.5.linux-amd64.tar.gz
Installez Go dans la VM. Pour en savoir plus, consultez Install Go (Installer Go).
Pour créer un répertoire pour le service Web, exécutez la commande suivante :
mkdirSERVICE_REPOcdSERVICE_REPO
Remarques supplémentaires
Lorsque vous créez un service Web, tenez compte des points suivants :
Les entrées dont vous avez besoin lors de la création de la VM sont disponibles en tant que variables d'environnement et portent le préfixe CONNECTOR_ENV_.
Lorsque vous configurez le service Web, utilisez les variables d'environnement pour lire ces valeurs.
Seules les valeurs requises pour configurer le service Web doivent être utilisées en tant qu'entrées lors de la création de la VM.
Le port du service doit être utilisé en tant qu'entrée à partir de la variable CONNECTOR_ENV_PORT.
Utilisez d'autres variables d'environnement pour les entrées facultatives.
Vous pouvez également obtenir des entrées lors de la création de la connexion. Vous pouvez définir ces champs lorsque vous créez le connecteur personnalisé et les transmettre en tant que chemin d'accès, requête ou en-têtes dans chaque appel d'API.
Assurez-vous que le serveur s'exécute sur localhost.
Journalisation
Consignez les informations requises et transférez les journaux à Cloud Logging. Cela permet aux utilisateurs de connecteurs de suivre et de déboguer les échecs. Pour publier des journaux dans Cloud Logging, vous pouvez utiliser le client Cloud Logging disponible dans Go : https://pkg.go.dev/cloud.google.com/go/logging#NewClient.
Vous devez initialiser l'enregistreur dans "main" et ajouter un middleware dans Gin pour suivre toutes les requêtes entrantes. Vous devez suivre la méthode, le chemin d'accès, l'état et la latence d'une requête. Pour filtrer les journaux, utilisez le niveau de gravité approprié lors de la journalisation. Dans le service Web, lisez le niveau de journalisation à partir de la variable d'environnement. Le niveau de journalisation est considéré comme une entrée facultative lors de la création de la VM. Par défaut, les journaux de niveau INFO peuvent être utilisés. Voici les niveaux de journalisation :
DEBUG : consigne chaque partie de la requête, y compris les traces de requête/réponse HTTP.
INFO : consigne le démarrage et l'arrêt du service, les requêtes et d'autres informations.
ERROR : consigne l'échec de la requête, les exceptions de mise en forme et d'autres erreurs.
Arrêt progressif
Configurez le serveur pour qu'il s'arrête progressivement et gère les requêtes en cours. Pour savoir comment redémarrer ou arrêter le serveur en douceur, consultez Graceful restart or stop (Redémarrage ou arrêt en douceur).
Simultanéité
Les serveurs Gin acceptent de manière inhérente les requêtes simultanées à l'aide de routines Go. Par défaut, les routines Go peuvent traiter un nombre indéfini de requêtes. Toutefois, dans certains cas, lorsque les requêtes sont censées nécessiter beaucoup de ressources, utilisez des pools de nœuds de calcul pour limiter et mettre en mémoire tampon les requêtes sur le serveur. Pour en savoir plus, consultez l'exemple de pools de nœuds de calcul.
Tester et créer le binaire
Définissez le port et exécutez le serveur à l'aide des commandes suivantes :
EXPORTCONNECTOR_ENV_PORT=8081
goget.
gorun.
Ces commandes regroupent les bibliothèques requises et exécutent le serveur.
Pour vérifier le serveur, exécutez la commande curl suivante sur la VM :
curl-XPOST-H"Content-Type: application/json"-H"X-Custom-Header: MyValue"-d'{"name": "Alice", "address": "123 Main St", "gender": "F"}'http://localhost:8081/postData/456
Créez le conteneur de connecteurs à l'aide de la commande suivante :
sudodockerbuild-tconnector-container.
Exécutez le conteneur Docker. Définissez --restart=unless-stopped pour redémarrer le service en cas d'échec inattendu.
Tâche au niveau du conteneur
Tous les journaux in stdout peuvent être acheminés vers Cloud Logging à l'aide du pilote de journal gcplogs lors de l'exécution du conteneur Docker. Cela permet de suivre le démarrage, l'échec inattendu ou l'arrêt inopiné du service.
Pour acheminer les journaux vers Cloud Logging, exécutez la commande suivante :
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/04 (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/04 (UTC)."],[[["\u003cp\u003eThis guide explains how to create a web service within a VM using the Gin web framework in Golang, but you can use any framework you wish.\u003c/p\u003e\n"],["\u003cp\u003eThe service must use environment variables with the prefix \u003ccode\u003eCONNECTOR_ENV_\u003c/code\u003e to read required inputs, including the service port specified by \u003ccode\u003eCONNECTOR_ENV_PORT\u003c/code\u003e, during VM creation or connection creation.\u003c/p\u003e\n"],["\u003cp\u003eThe guide details logging practices, instructing to push logs to Cloud Logging using the provided Go client and to track method, path, status, and latency for each request, along with specifying the available log levels (DEBUG, INFO, ERROR).\u003c/p\u003e\n"],["\u003cp\u003eIt is essential to set up the server for a graceful shutdown to handle requests in progress and use concurrency features provided by Gin to manage multiple requests, along with managing resource usage via worker pools.\u003c/p\u003e\n"],["\u003cp\u003eThe process includes steps to test and build the service binary, run the server, verify its operation with curl commands, containerize the application using Docker, and route logs to Cloud Logging.\u003c/p\u003e\n"]]],[],null,["# Create a web service\n\n| **Preview**\n|\n|\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nCreate a web service\n====================\n\n\nThis page describes how to create a web service in the VM using the Gin web framework that is written in Golang. You can choose to create the web service in any other framework that you want to use.\n\n1. To download the Go package in the VM, run the following command in the VM: \n\n ```bash\n wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz\n \n ```\n2. Install Go in the VM. For information, see [Install Go](https://go.dev/doc/install).\n3. To create a new directory for the web service, run the following command: \n\n ```bash\n mkdir SERVICE_REPO\n cd SERVICE_REPO\n \n ```\n\n### Additional considerations\n\n\nWhen you create a web service, you must be aware of the following considerations:\n\n- Inputs that you require during VM creation are available as environment variables and have the following prefix: `CONNECTOR_ENV_`.\n- When you set up the web service, use the environment variables to read such values.\n- Only values that are required to set up the web service must be taken as input during the VM creation.\n- The port of the service must be taken as input from the CONNECTOR_ENV_PORT variable.\n- Use other environment variables for optional inputs.\n- You can also get inputs during connection creation. You can define these fields when you create the custom connector and pass them as path, query, or headers in each API call.\n- Ensure that the server runs on the localhost.\n\n### Logging\n\n\nLog the required information and push the logs to Cloud Logging. This helps connector consumers track and debug failures. To publish logs to Cloud Logging, you can use the following Cloud Logging\nclient available in Go: \u003chttps://pkg.go.dev/cloud.google.com/go/logging#NewClient\u003e\n\n\nYou must initialize the logger in main and add a middleware in Gin to track all the incoming requests. You must track the method, path, status, and latency for a request. To filter the logs, use the appropriate severity while logging. In the web service, read the log level from the environment variable. The log level is taken as optional input from during the VM creation. By default, Info logs can be used. The following are the log levels:\n\n- DEBUG: logs every part of the request including the HTTP request/response traces.\n- INFO: logs service startup, service shutdown, requests, and other information.\n- ERROR: logs request failure, formatting exceptions, and other errors.\n\n### Graceful shutdown\n\n\nSet up the server to gracefully shutdown and handle the in progress requests. For information about how to gracefully restart or stop the server, see [Graceful restart or stop](https://gin-gonic.com/docs/examples/graceful-restart-or-stop/).\n\n### Concurrency\n\n\nGin servers inherently support concurrent requests using Go routines. By default, an undefined number of requests are allowed to be processed by Go routines. However, in some cases, when requests are expected to be resource intensive, use worker pools to restrict and buffer the requests on the server. For more information, see [Worker pools example](https://gobyexample.com/worker-pools).\n\n### Test and build the binary\n\n1. Set the port and run the server by using the following commands: \n\n```bash\nEXPORT CONNECTOR_ENV_PORT = 8081\ngo get .\ngo run .\n```\n2. These commands bundle the required libraries and run the server.\n3. To verify the server, run the following curl command on the VM: \n\n ```bash\n curl -X POST -H \"Content-Type: application/json\" -H \"X-Custom-Header: MyValue\" -d '{\"name\": \"Alice\", \"address\": \"123 Main St\", \"gender\": \"F\"}' http://localhost:8081/postData/456\n ``` \n\n ```bash\n curl -v http://localhost:8081/getData -H \"TestKey: MyValue\"\n ```\n4. Create the binary and use it as the VM image by using the following command: \n\n ```bash\n go build -o SERVICE_NAME\n ```\n5. Move the binary to the root folder by using the following command: \n\n ```bash\n sudo cp SERVICE_NAME /opt\n ```\n6. Run the service again to verify that the binary is working as expected by using the following command: \n\n ```bash\n sudo chmod +x SERVICE_NAME\n ./SERVICE_NAME\n ```\n\n### Containerize the application\n\n1. Install Docker. For information, see [Install Docker](https://docs.docker.com/engine/install/debian/).\n2. Create a Docker file to run binaries. \n\n ```bash\n FROM alpine:latest\n WORKDIR /opt\n COPY . .\n CMD [\"./\u003cvar translate=\"no\"\u003eSERVICE_NAME\u003c/var\u003e\"]\n ```\n3. Build the connector container by using the following command: \n\n ```bash\n sudo docker build -t connector-container .\n ```\n4. Run the docker container. Set `--restart=unless-stopped` to restart the service in case of unexpected failure.\n\n#### Container level task\n\n\nAll logs in stdout can be routed to Cloud Logging by using the gcplogs Log driver while running the docker container. This helps to track the startup or unexpected failure or shutdown of the service.\nTo route the logs to Cloud Logging, run the following command: \n\n```bash\n sudo docker run --name connector-service -e\n CONNECTOR_ENV_PORT=$CONNECTOR_ENV_PORT -p\n $CONNECTOR_ENV_PORT:$CONNECTOR_ENV_PORT --restart=unless-stopped ----log-driver=gcplogs connector-container\n```\n\nWhat's next\n-----------\n\n- Learn how to [create a custom connector](/integration-connectors/docs/marketplace/create-custom-connector)."]]