跳转到内容
搜索文档

使用同 URL 直接访问进行 A/B 测试

根据 Cookie 控制所提供的响应,从而设置 A/B 测试。

最后更新 查看 MarkdownAgent 设置

此版本将针对 /test/*/control/* URI 路径的请求直接透传到源站服务器,从而绕过随机分配。

const NAME = "myExampleABTest";

export default {
	async fetch(request) {
		// Clone the original URL
		const url = new URL(request.url);

		// Enable Passthrough to allow direct access to control and test routes.
		if (url.pathname.startsWith("/control") || url.pathname.startsWith("/test"))
			return fetch(request);

		// Determine which group this requester is in.
		const cookie = request.headers.get("cookie");

		if (cookie && cookie.includes(`${NAME}=control`)) {
			url.pathname = "/control" + url.pathname;
		} else if (cookie && cookie.includes(`${NAME}=test`)) {
			url.pathname = "/test" + url.pathname;
		} else {
			// If there is no cookie, this is a new client. Choose a group and set the cookie.
			const group = Math.random() < 0.5 ? "test" : "control"; // 50/50 split
			if (group === "control") {
				url.pathname = "/control" + url.pathname;
			} else {
				url.pathname = "/test" + url.pathname;
			}
			// Reconstruct response to avoid immutability
			let response = await fetch(url);
			response = new Response(response.body, response);
			// Set cookie to enable persistent A/B sessions.
			response.headers.append("Set-Cookie", `${NAME}=${group}; path=/`);
			return response;
		}
		return fetch(url);
	},
};

这篇文档对您有帮助吗?