Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Crea un servicio web
En esta página, se describe cómo crear un servicio web en la VM con el framework web Gin escrito en Golang. Puedes crear el servicio web en cualquier otro framework que desees usar.
Para descargar el paquete de Go en la VM, ejecuta el siguiente comando en la VM:
wgethttps://go.dev/dl/go1.22.5.linux-amd64.tar.gz
Instala Go en la VM. Para obtener más información, consulta Instala Go.
Para crear un directorio nuevo para el servicio web, ejecuta el siguiente comando:
mkdirSERVICE_REPOcdSERVICE_REPO
Consideraciones adicionales
Cuando crees un servicio web, debes tener en cuenta los siguientes factores:
Las entradas que necesitas durante la creación de la VM están disponibles como variables de entorno y tienen el siguiente prefijo: CONNECTOR_ENV_.
Cuando configures el servicio web, usa las variables de entorno para leer esos valores.
Solo se deben tomar como entrada los valores necesarios para configurar el servicio web durante la creación de la VM.
El puerto del servicio debe tomarse como entrada de la variable CONNECTOR_ENV_PORT.
Usa otras variables de entorno para las entradas opcionales.
También puedes obtener entradas durante la creación de la conexión. Puedes definir estos campos cuando creas el conector personalizado y pasarlos como ruta, consulta o encabezados en cada llamada a la API.
Asegúrate de que el servidor se ejecute en localhost.
Logging
Registra la información requerida y envía los registros a Cloud Logging. Esto ayuda a los consumidores del conector a hacer un seguimiento de las fallas y depurarlas. Para publicar registros en Cloud Logging, puedes usar el siguiente cliente de Cloud Logging disponible en Go: https://pkg.go.dev/cloud.google.com/go/logging#NewClient
Debes inicializar el registrador en main y agregar un middleware en Gin para hacer un seguimiento de todas las solicitudes entrantes. Debes hacer un seguimiento del método, la ruta, el estado y la latencia de una solicitud. Para filtrar los registros, usa la gravedad adecuada durante el registro. En el servicio web, lee el nivel de registro de la variable de entorno. El nivel de registro se toma como entrada opcional durante la creación de la VM. De forma predeterminada, se pueden usar los registros de información. Estos son los niveles de registro:
DEBUG: Registra cada parte de la solicitud, incluidos los registros de seguimiento de la solicitud/respuesta HTTP.
INFO: Registra el inicio y el cierre del servicio, las solicitudes y otra información.
ERROR: Registra fallas en las solicitudes, excepciones de formato y otros errores.
Cierre ordenado
Configura el servidor para que se apague de forma correcta y controle las solicitudes en curso. Para obtener información sobre cómo reiniciar o detener el servidor de forma ordenada, consulta Reinicio o detención ordenados.
Simultaneidad
Los servidores de Gin admiten inherentemente solicitudes simultáneas con rutinas de Go. De forma predeterminada, se permite que las rutinas de Go procesen una cantidad indefinida de solicitudes. Sin embargo, en algunos casos, cuando se espera que las solicitudes consuman muchos recursos, usa grupos de trabajadores para restringir y almacenar en búfer las solicitudes en el servidor. Para obtener más información, consulta el ejemplo de grupos de trabajadores.
Cómo probar y compilar el objeto binario
Configura el puerto y ejecuta el servidor con los siguientes comandos:
EXPORTCONNECTOR_ENV_PORT=8081
goget.
gorun.
Estos comandos agrupan las bibliotecas requeridas y ejecutan el servidor.
Para verificar el servidor, ejecuta el siguiente comando curl en 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
Compila el contenedor del conector con el siguiente comando:
sudodockerbuild-tconnector-container.
Ejecuta el contenedor de Docker. Establece --restart=unless-stopped para reiniciar el servicio en caso de falla inesperada.
Tarea a nivel del contenedor
Todos los registros en stdout se pueden enrutar a Cloud Logging con el controlador de registros gcplogs mientras se ejecuta el contenedor de Docker. Esto ayuda a hacer un seguimiento del inicio, la falla inesperada o el apagado del servicio.
Para enrutar los registros a Cloud Logging, ejecuta el siguiente comando:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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)."]]