Skip to content

Instantly share code, notes, and snippets.

@alicancakil
Last active September 2, 2021 02:44
Show Gist options
  • Save alicancakil/d4fd8edb40e3e47d5917de2baa344b7a to your computer and use it in GitHub Desktop.
Save alicancakil/d4fd8edb40e3e47d5917de2baa344b7a to your computer and use it in GitHub Desktop.
Checks to see if there is an internet connection
const getContent = function (url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
};
exports.handler = async (event) => {
console.log('Received event: %j', event);
const url = event.url || 'https://ipaddress.ai/json';
try {
const content = await getContent(url);
console.log('Response content: %j', content);
console.log('Fuck yea, we have access to the internet!');
return {
statusCode: 200,
body: JSON.stringify({
message: 'You have access!',
content,
}),
};
} catch (e) {
console.error(e);
return {
statusCode: 500,
body: JSON.stringify({
message: e.toString(),
}),
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment