以下是一个使用AWS Lambda函数来检查站点是否可用的示例代码:
import urllib.request
import json
def lambda_handler(event, context):
# URL to check
url = 'https://example.com'
try:
# Open the URL and read the response
response = urllib.request.urlopen(url)
data = response.read()
# Check the status code of the response
if response.status == 200:
# Site is available
return {
'statusCode': 200,
'body': json.dumps('Site is available')
}
else:
# Site is not available
return {
'statusCode': response.status,
'body': json.dumps('Site is not available')
}
except Exception as e:
# An error occurred while opening the URL
return {
'statusCode': 500,
'body': json.dumps(str(e))
}
在上面的代码中,我们使用了urllib.request.urlopen()
函数来打开指定的URL,并读取响应。然后,我们检查响应的状态码,如果状态码为200,则表示站点可用;如果状态码不为200,则表示站点不可用。
在Lambda函数的配置中,可以设置定期触发器,例如每隔5分钟触发一次函数。这样,Lambda函数将会定期检查站点的可用性,并根据结果返回相应的响应。
注意:在使用Lambda函数时,需要确保函数位于具有Internet访问权限的VPC中,以便能够访问外部资源。