Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Criar um serviço da Web
Nesta página, descrevemos como criar um serviço da Web na VM usando o framework da Web Gin, escrito em Golang. Você pode criar o serviço da Web em qualquer outro framework que quiser usar.
Para fazer o download do pacote Go na VM, execute o seguinte comando:
wgethttps://go.dev/dl/go1.22.5.linux-amd64.tar.gz
Instale o Go na VM. Para mais informações, consulte Instalar o Go.
Para criar um diretório para o serviço da Web, execute o seguinte comando:
mkdirSERVICE_REPOcdSERVICE_REPO
Outras considerações
Ao criar um serviço da Web, você precisa estar ciente das seguintes considerações:
As entradas necessárias durante a criação da VM estão disponíveis como variáveis de ambiente e têm o seguinte prefixo: CONNECTOR_ENV_.
Ao configurar o serviço da Web, use as variáveis de ambiente para ler esses valores.
Apenas os valores necessários para configurar o serviço da Web precisam ser usados como entrada durante a criação da VM.
A porta do serviço precisa ser usada como entrada da variável CONNECTOR_ENV_PORT.
Use outras variáveis de ambiente para entradas opcionais.
Você também pode receber entradas durante a criação da conexão. É possível definir esses campos ao criar o conector personalizado e transmiti-los como caminho, consulta ou cabeçalhos em cada chamada de API.
Verifique se o servidor está sendo executado no localhost.
Logging
Registre as informações necessárias e envie os registros para o Cloud Logging. Isso ajuda os consumidores do conector a rastrear e depurar falhas. Para publicar registros no Cloud Logging, use o seguinte cliente do Cloud Logging disponível em Go: https://pkg.go.dev/cloud.google.com/go/logging#NewClient
Inicialize o logger na função principal e adicione um middleware no Gin para rastrear todas as solicitações recebidas. É necessário rastrear o método, o caminho, o status e a latência de uma solicitação. Para filtrar os registros, use a gravidade adequada ao fazer o registro. No serviço da Web, leia o nível de registro da variável de ambiente. O nível de registro é considerado uma entrada opcional durante a criação da VM. Por padrão, os registros de informações podem ser usados. Estes são os níveis de registro:
DEBUG: registra todas as partes da solicitação, incluindo os rastreamentos de solicitação/resposta HTTP.
INFO: registra a inicialização e o encerramento do serviço, solicitações e outras informações.
ERROR: registra falhas de solicitação, exceções de formatação e outros erros.
Encerramento sem dificuldades
Configure o servidor para desligar normalmente e processar as solicitações em andamento. Para informações sobre como reiniciar ou interromper o servidor normalmente, consulte Reinicialização ou interrupção normal.
Simultaneidade
Os servidores Gin oferecem suporte inerente a solicitações simultâneas usando rotinas Go. Por padrão, um número indefinido de solicitações pode ser processado por rotinas do Go. No entanto, em alguns casos, quando as solicitações devem consumir muitos recursos, use pools de workers para restringir e armazenar em buffer as solicitações no servidor. Para mais informações, consulte Exemplo de pools de workers.
Testar e criar o binário
Defina a porta e execute o servidor usando os seguintes comandos:
EXPORTCONNECTOR_ENV_PORT=8081
goget.
gorun.
Esses comandos agrupam as bibliotecas necessárias e executam o servidor.
Para verificar o servidor, execute o seguinte comando curl na 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
Crie o contêiner do conector usando o seguinte comando:
sudodockerbuild-tconnector-container.
Execute o contêiner do Docker. Defina --restart=unless-stopped para reiniciar o serviço em caso de falha inesperada.
Tarefa no nível do contêiner
Todos os registros em stdout podem ser encaminhados para o Cloud Logging usando o driver de registro gcplogs ao executar o contêiner do Docker. Isso ajuda a rastrear a inicialização ou falha ou encerramento inesperado do serviço.
Para encaminhar os registros ao Cloud Logging, execute o seguinte comando:
[[["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-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)."]]