Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Membuat layanan web
Halaman ini menjelaskan cara membuat layanan web di VM menggunakan framework web Gin yang ditulis dalam Golang. Anda dapat memilih untuk membuat layanan web di framework lain yang ingin Anda gunakan.
Untuk mendownload paket Go di VM, jalankan perintah berikut di VM:
wgethttps://go.dev/dl/go1.22.5.linux-amd64.tar.gz
Instal Go di VM. Untuk mengetahui informasinya, lihat Menginstal Go.
Untuk membuat direktori baru bagi layanan web, jalankan perintah berikut:
mkdirSERVICE_REPOcdSERVICE_REPO
Pertimbangan lainnya
Saat membuat layanan web, Anda harus mengetahui pertimbangan berikut:
Input yang Anda perlukan selama pembuatan VM tersedia sebagai variabel lingkungan dan memiliki awalan berikut: CONNECTOR_ENV_.
Saat menyiapkan layanan web, gunakan variabel lingkungan untuk membaca nilai tersebut.
Hanya nilai yang diperlukan untuk menyiapkan layanan web yang harus diambil sebagai input selama pembuatan VM.
Port layanan harus diambil sebagai input dari variabel CONNECTOR_ENV_PORT.
Gunakan variabel lingkungan lain untuk input opsional.
Anda juga bisa mendapatkan input selama pembuatan koneksi. Anda dapat menentukan kolom ini saat membuat konektor kustom dan meneruskannya sebagai jalur, kueri, atau header di setiap panggilan API.
Pastikan server berjalan di localhost.
Logging
Catat informasi yang diperlukan dan kirim log ke Cloud Logging. Hal ini membantu konsumen konektor melacak dan men-debug kegagalan. Untuk memublikasikan log ke Cloud Logging, Anda dapat menggunakan klien Cloud Logging berikut yang tersedia di Go: https://pkg.go.dev/cloud.google.com/go/logging#NewClient
Anda harus melakukan inisialisasi logger di main dan menambahkan middleware di Gin untuk melacak semua permintaan masuk. Anda harus melacak metode, jalur, status, dan latensi untuk permintaan. Untuk memfilter log, gunakan tingkat keparahan yang sesuai saat mencatat log. Di layanan web, baca tingkat log dari variabel lingkungan. Tingkat log diambil sebagai input opsional selama pembuatan VM. Secara default, log Info dapat digunakan. Berikut adalah level log:
DEBUG: mencatat setiap bagian permintaan, termasuk rekaman aktivitas permintaan/respons HTTP.
INFO: mencatat startup layanan, penonaktifan layanan, permintaan, dan informasi lainnya.
ERROR: mencatat kegagalan permintaan, pengecualian pemformatan, dan error lainnya.
Penghentian tuntas
Siapkan server untuk mematikan secara halus dan menangani permintaan yang sedang diproses. Untuk mengetahui informasi tentang cara memulai ulang atau menghentikan server dengan benar, lihat Memulai ulang atau menghentikan dengan benar.
Serentak
Server Gin secara inheren mendukung permintaan serentak menggunakan rutin Go. Secara default, sejumlah permintaan yang tidak ditentukan diizinkan untuk diproses oleh rutin Go. Namun, dalam beberapa kasus, saat permintaan diperkirakan akan menggunakan banyak resource, gunakan kumpulan pekerja untuk membatasi dan mem-buffer permintaan di server. Untuk mengetahui informasi selengkapnya, lihat Contoh kumpulan pekerja.
Menguji dan membangun biner
Tetapkan port dan jalankan server menggunakan perintah berikut:
EXPORTCONNECTOR_ENV_PORT=8081
goget.
gorun.
Perintah ini menggabungkan library yang diperlukan dan menjalankan server.
Untuk memverifikasi server, jalankan perintah curl berikut di 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
Bangun container konektor menggunakan perintah berikut:
sudodockerbuild-tconnector-container.
Jalankan container Docker. Tetapkan --restart=unless-stopped untuk memulai ulang layanan jika terjadi kegagalan yang tidak terduga.
Tugas tingkat penampung
Semua log di stdout dapat dirutekan ke Cloud Logging menggunakan driver Log gcplogs saat menjalankan container Docker. Hal ini membantu melacak startup atau kegagalan atau penonaktifan layanan yang tidak terduga.
Untuk merutekan log ke Cloud Logging, jalankan perintah berikut:
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 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)."]]