GetFunctionUrlConfigCommand 的使用
在代码中调用时可以如下
const { LambdaClient, GetFunctionUrlConfigCommand } = require("@aws-sdk/client-lambda");
/**
* Function to GetFunctionUrlConfig Lambda.
* @param {*} lambdaName lambdaName
* @param {*} region region
* @returns {object} FunctionUrlConfig
*/
async function GetFunctionUrlConfigLambda(lambdaName, region) {
const client = new LambdaClient({ region: region });
const getFunctionUrlConfigParam = {
FunctionName: lambdaName,
};
return await client.send(new GetFunctionUrlConfigCommand(getFunctionUrlConfigParam));
}
- 使用的时候注意要加上try catch,因为在调用GetFunctionUrlConfigLambda时如果传入的lambdaName在指定的区域中并不存在,并不会返回空,而是会抛出异常。所以得用try catch来处理,而非用if判断是否为空。
try {
functionUrlConfigCommandResponse = await GetFunctionUrlConfigLambda(lambdaName, "US-1");
} catch (error) {}
lambda@Edge作成
如果要做一个对源响应的重定向,我们要修改的是传入lamdba的request
const request = event.Records[0].cf.request;
要改为如下格式,不然会出问题 backupOriginDomain是通过取GetFunctionUrlConfigCommand 出来的FunctionUrl的hostname
try {
functionUrlConfig = await GetFunctionUrlConfigLambda(lambdaName, "us-1");
} catch (error) {
}
const backupOriginDomain = new URL(functionUrlConfig.FunctionUrl).hostname;
request.origin = {
custom: {
domainName: backupOriginDomain,
port: 443,
protocol: "https",
path: "",
sslProtocols: ["TLSv1", "TLSv1.1", "TLSv1.2"],
readTimeout: 5,
keepaliveTimeout: 5,
customHeaders: {},
},
};
request.headers["host"] = [
{
key: "host",
value: backupOriginDomain,
},
];
lambda@Edge 所绑定的lambdaFunction
绑定的前提
- 没有自定义的环境变量
- function的role 的Trust relationship中的 Service要追加lambda.amazonaws.com权限
- 使用的lambdaFunction要发布版本,并且绑定lambda@Edge用的arn是所发布版本的arn
返回的响应数据格式
status,statusDescription,body,headers这几个属性是一定要有的,否则会导致代码报错
{
status: 503,
statusDescription: "Service Unavailable",
body: JSON.stringify({
message,
error_id: errorId,
env_info: envInfo,
}),
headers: {
"content-type": [{ key: "Content-Type", value: "application/json"}],
},
}