|
5 | 5 | export default { |
6 | 6 | async fetch(request, env) { |
7 | 7 | const url = new URL(request.url); |
8 | | - const cookieName = "ab-homepage-test-cookie"; |
9 | | - const newHomepagePathName = "/index-test"; |
10 | | - let cookie = request.headers.get("cookie"); |
11 | | - if (url.pathname === ('/api/fred')) { |
12 | | - // TODO: Add custom logic here. |
13 | | - url.pathname = newHomepagePathName; |
| 8 | + const cookieName = "test-ab-cookie"; |
| 9 | + const PathNameA = "/test-a"; |
| 10 | + const PathNameB = "/test-b"; |
14 | 11 |
|
15 | | - const percentage = Math.floor(Math.random() * 100); |
16 | | - let version = "current"; // default version |
17 | | - // change pathname and version name for 50% of traffic |
18 | | - if (percentage < 50) { |
19 | | - url.pathname = newHomepagePathName; |
20 | | - version = "new"; |
| 12 | + if (url.pathname === ('/landing')) { |
| 13 | + |
| 14 | + let cookie = request.headers.get("cookie"); |
| 15 | + if (cookie && cookie.includes(`${cookieName}=A`)) { |
| 16 | + url.pathname = PathNameA |
| 17 | + return env.ASSETS.fetch(url) |
| 18 | + } |
| 19 | + else if (cookie && cookie.includes(`${cookieName}=B`)) { |
| 20 | + url.pathname = PathNameB |
| 21 | + return env.ASSETS.fetch(url) |
21 | 22 | } |
22 | | - // get the static file from ASSETS, and attach a cookie |
23 | | - const asset = await env.ASSETS.fetch(url); |
24 | | - let response = new Response(asset.body, asset); |
25 | | - let expires = (new Date(Date.now()+ 86400*1000)).toUTCString(); // Valid for 1 Day = 24 Hrs = 24*60*60 = 86400. |
26 | | - response.headers.append("Set-Cookie", `${cookieName}=${version}; expires= ${expires} ;path=/`); |
27 | | - return response; |
| 23 | + else { |
| 24 | + url.pathname = PathNameB; |
| 25 | + |
| 26 | + const percentage = Math.floor(Math.random() * 100); |
| 27 | + let version = "A"; // default version |
28 | 28 |
|
| 29 | + // change pathname and version name for 50% of traffic |
| 30 | + if (percentage < 50) { |
| 31 | + url.pathname = PathNameB; |
| 32 | + version = "B"; |
| 33 | + } |
| 34 | + // get the static file from ASSETS, and attach a cookie |
| 35 | + const asset = await env.ASSETS.fetch(url); |
| 36 | + let response = new Response(asset.body, asset); |
| 37 | + let expires = (new Date(Date.now()+ 86400*1000)).toUTCString(); // Valid for 1 Day = 24 Hrs = 24*60*60 = 86400. |
| 38 | + response.headers.append("Set-Cookie", `${cookieName}=${version}; expires= ${expires} ;path=/`); |
| 39 | + return response; |
| 40 | + } |
29 | 41 | } |
30 | | - // Otherwise, serve the static assets. |
| 42 | + // Otherwise, serve the static assets for the current page being requested. |
31 | 43 | // Without this, the Worker will error and no assets will be served. |
32 | 44 | return env.ASSETS.fetch(request); |
33 | 45 | }, |
|
0 commit comments