INTEGRITY Dokumentace

Směrování k privátním službám z Workers

Tento příklad ukazuje, jak pomocí Workers VPC vytvořit centralizovanou bránu, která směruje požadavky podle cest URL, zajišťuje ověřování a omezování počtu požadavků a rozkládá zátěž mezi interní služby.

Předpoklady

1. Vytvořte VPC Services

Nejprve vytvořte služby pro svá interní API pomocí hostname:

# Create user service
npx wrangler vpc service create user-service \
  --type http \
  --tunnel-id <YOUR_TUNNEL_ID> \
  --hostname user-api.internal.example.com

# Create orders service
npx wrangler vpc service create order-service \
  --type http \
  --tunnel-id <YOUR_TUNNEL_ID> \
  --hostname orders-api.internal.example.com

Poznamenejte si ID služeb vrácená pro další krok.

2. Konfigurace Workeru

Upravte konfigurační soubor Wrangler:

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "api-gateway",
	"main": "src/index.js",
	// Set this to today's date
	"compatibility_date": "2026-08-28",
	"vpc_services": [
		{
			"binding": "USER_SERVICE",
			"service_id": "<YOUR_USER_SERVICE_ID>"
		},
		{
			"binding": "ORDER_SERVICE",
			"service_id": "<YOUR_ORDER_SERVICE_ID>"
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "api-gateway"
main = "src/index.js"
# Set this to today's date
compatibility_date = "2026-08-28"

[[vpc_services]]
binding = "USER_SERVICE"
service_id = "<YOUR_USER_SERVICE_ID>"

[[vpc_services]]
binding = "ORDER_SERVICE"
service_id = "<YOUR_ORDER_SERVICE_ID>"

3. Implementujte Worker

Ve svém kódu Workers použijte bindingy VPC Service ke směrování požadavků na příslušné služby:

index.js
export default {
	async fetch(request, env, ctx) {
		const url = new URL(request.url);

		// Route to internal services
		if (url.pathname.startsWith('/api/users')) {
			const response = await env.USER_SERVICE.fetch("https://user-api.internal.example.com" + url.pathname);
			return response;
		} else if (url.pathname.startsWith('/api/orders')) {
			const response = await env.ORDER_SERVICE.fetch("https://orders-api.internal.example.com" + url.pathname);
			return response;
		}

		return new Response('Not Found', { status: 404 });
	},
};

4. Nasaďte a otestujte

Nyní můžete nasadit a otestovat svůj Worker:

npx wrangler deploy
# Test user service requests
curl https://api-gateway.workers.dev/api/users

# Test orders service requests
curl https://api-gateway.workers.dev/api/orders

Další kroky