簡體   English   中英

AWS Lambda 僅在滿足條件時觸發 function

[英]AWS Lambda trigger function only if conditions are met

我剛剛開始學習 AWS Lambda 和 CloudFront。 我發現操作請求和響應非常容易,但是我無法完成一個簡單的任務。

鑒於下面的代碼,我只想在用戶在request.uri中沒有 /it/ 或 /en/ 的情況下觸發操作

我在解析 uri 字符串時沒有問題,但我不確定如何實現這個非常簡單的邏輯:

if(uri contains 'it' or 'en') {
  proceed as normal and forward request to origin
} else {
  return a 301 response with '/it' or '/en' based on user language
}

下面用 node.js 編寫的 function 部分完成了這項工作,它在我的 CloudFront 分配的Viewer Request中觸發:

exports.handler = async (event, context, callback) => {

    // const
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    // non IT url
    let url = '/en/';
    if (headers['cloudfront-viewer-country']) {
        const countryCode = headers['cloudfront-viewer-country'][0].value;
        if (countryCode === 'IT') {
            url = '/it/';
        }
    }

    const response = {
        status: '301',
        statusDescription: 'geolocation',
        headers: {
            location: [{
                key: 'Location',
                value: url,
            }],
        },
    };

    callback(null, response);  
};

如果我沒有錯,那么您缺少的部分就是if ,因為您只有else

exports.handler = async (event, context, callback) => {

    // const
    const request = event.Records[0].cf.request;
    const headers = request.headers;


    if (headers['cloudfront-viewer-country']) {
        // non IT url
        let url = '/en/';
        const countryCode = headers['cloudfront-viewer-country'][0].value;
        if (countryCode === 'IT') {
            url = '/it/';
        }

        const response = {
            status: '301',
            statusDescription: 'geolocation',
            headers: {
                location: [{
                    key: 'Location',
                    value: url,
                }],
            },
        };

        callback(null, response); 
    }

    // There is no need to redirect
    callback(null, request);

};

所以基本上如果 URL 有 IT 或 EN,就讓它 go 槽 whit: callback(null, request);

您可能會從對您的案例有用的文檔中找到此示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM