有奖捉虫:办公协同&微信生态&物联网文档专题 HOT
该示例通过 cookies 保存会话信息,对请求进行 A/B 测试控制。使用边缘函数实现了 A/B 测试的场景。

示例代码

// cookie 名称
const COOKIE_NAME = 'ABTest';

// cookie 值
const VALUE_A = 'index-a.html';
const VALUE_B = 'index-b.html';

// 根路径,要求源站存在该路径,并且该路径下有文件 index-a.html、index-b.html
const BASE_PATH = '/abtest';

async function handleRequest(request) {
const urlInfo = new URL(request.url);

// 判断 url 路径,若访问非 abtest 的资源,则直接响应。
if (!urlInfo.pathname.startsWith(BASE_PATH)) {
return fetch(request);
}

// 获取当前请求的 cookie
const cookies = new Cookies(request.headers.get('cookie'));
const abTestCookie = cookies.get(COOKIE_NAME);
const cookieValue = abTestCookie?.value;

// 如果 cookie 值为 A 测试,返回 index-a.html
if (cookieValue === VALUE_A) {
urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;
return fetch(urlInfo.toString());
}

// 如果 cookie 值为 B 测试,返回 index-b.html
if (cookieValue === VALUE_B) {
urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;
return fetch(urlInfo.toString());
}

// 不存在 cookie 信息,则随机分配当前请求走 A 或 B 测试
const testValue = Math.random() < 0.5 ? VALUE_A : VALUE_B;
urlInfo.pathname = `/${BASE_PATH}/${testValue}`;

const response = await fetch(urlInfo.toString());

cookies.set(COOKIE_NAME, testValue, { path: '/', max_age: 60 });
response.headers.set('Set-Cookie', getSetCookie(cookies.get(COOKIE_NAME)));
return response;
}

// 拼接 Set-Cookie
function getSetCookie(cookie) {
const cookieArr = [
`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,
];

const key2name = {
expires: 'Expires',
max_age: 'Max-Age',
domain: 'Domain',
path: 'Path',
secure: 'Secure',
httponly: 'HttpOnly',
samesite: 'SameSite',
};

Object.keys(key2name).forEach(key => {
if (cookie[key]) {
cookieArr.push(`${key2name[key]}=${cookie[key]}`);
}
});

return cookieArr.join('; ');
}

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

示例预览

在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,即可预览到示例效果。


相关参考