メニュー
Amazon CloudFront
開発者ガイド (API Version 2016-09-29)

関数の例

注記

各 Lambda@Edge 関数には、正常にリクエストを処理、またはレスポンスを返すために callback() 行が含まれている必要があります。詳細については、AWS Lambda Developer Guideの「Lambda@Edge 用の関数を認証する」を参照してください。

例: A/B テスト

以下は、クライアントの分類に基づく様々なコンテンツ提供を目的とするA/B テストの例です:

Copy
'use strict'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const headers = request.headers; if (request.uri !== '/experiment-pixel.jpg') { // do not process if this is not an A-B test request callback(null, request); } const experimentCookieName = 'X-Experiment-Name='; const groupA = 'A'; const groupB = 'B'; const groupAObject = '/experiment-group/control-pixel.jpg'; const groupBObject = '/experiment-group/treatment-pixel.jpg'; /* * Lambda at the Edge headers are array objects. * Client may send multiple Cookie headers, i.e.: * > GET /viewerRes/test HTTP/1.1 * > User-Agent: curl/7.18.1 (x86_64-unknown-linux-gnu) libcurl/7.18.1 OpenSSL/1.0.1u zlib/1.2.3 * > Cookie: First=1; Second=2 * > Cookie: ClientCode=abc * > Host: example.com * You can access the first Cookie line by * headers["Cookie"][0] * and the second by * headers["Cookie"][1] * headers["Cookie"][0] will return "First=1; Second=2", cookie tokens are not parsed * separately. */ if (headers.Cookie !== undefined) { for (let i = 0; i < headers.Cookie.length; i++) { const experimentIndex = headers.Cookie[i].indexOf(experimentCookieName); if (experimentIndex > 0) { if (headers.Cookie[i][experimentIndex + experimentCookieName.length] === groupA) { request.uri = groupAObject; callback(null, request); } if (headers.Cookie[i][experimentIndex + experimentCookieName.length] === groupB) { request.uri = groupBObject; callback(null, request); } } } } /* * This is the first time the viewer is * requesting this, so randomly distribute them */ if (Math.random() < 0.75) { // 75% of the viewers go to group A. request.uri = groupAObject; } else { request.uri = groupBObject; } callback(null, event.Records[0].cf.request); };

例: レスポンスのヘッダーのオーバーライド

以下は、別のヘッダーから提供される値に基づく、既存のヘッダーのレスポンス例です。

Copy
'use strict'; exports.handler = (event, context, callback) => { const headers = event.Records[0].cf.response.headers; const customHeaderName = 'X-Amz-Meta-Last-Modified'; const headerNameToBeChanged = 'Last-Modified'; if (headers[customHeaderName] !== undefined) { headers[headerNameToBeChanged] = headers[customHeaderName]; } callback(null, event.Records[0].cf.response); }; }