Return 如果密钥在 VTL 中不存在则为 null / API 网关模板

Return null if key does not exist in VTL / API Gateway Template

以下模板 returns '' 如果授权 header 存在。我怎样才能得到 null 呢?所以 return null 如果密钥不存在...

{
  "headers" : { 
     "authorization" : "$input.params().header.get('Authorization')" 
  }
}

您可以使用 #if ($variable) 检查变量是否 not null

#if ($variable) 
   ... do stuff here if the variable is not null
#end

在您的用例中,您可以尝试对授权 header 进行空检查,就像这样。

{
  "headers" : {
     #if( $input.params().header.get('Authorization').toString() != "" ) 
        "authorization" : "$input.params().header.get('Authorization')" 
     #end
  }
}