Gin サーバーは、Go ルーティンを使用して同時リクエストをネイティブにサポートしています。デフォルトでは、未定義の数のリクエストが Go ルーティンで処理されます。ただし、リクエストがリソースを大量に消費することが予想される場合は、ワーカープールを使用してサーバー上のリクエストを制限し、バッファリングします。詳細については、ワーカープールの例をご覧ください。
バイナリをテストしてビルドする
次のコマンドを使用してポートを設定し、サーバーを実行します。
EXPORTCONNECTOR_ENV_PORT=8081
goget.
gorun.
これらのコマンドは、必要なライブラリをバンドルしてサーバーを実行します。
サーバーを確認するには、VM で次の curl コマンドを実行します。
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
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 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)."]]