Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Created September 2, 2018 08:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoarLin/3cc22f8745ca6a7d81182332d7d1c6e3 to your computer and use it in GitHub Desktop.
Save SoarLin/3cc22f8745ca6a7d81182332d7d1c6e3 to your computer and use it in GitHub Desktop.
AWS Lambda Function to Get Internet IP
const http = require('http');
exports.handler = function(event, context, callback) {
const option = {
"hostname": "api.ipify.org",
"path": "/?format=JSON",
"method": "GET"
};
callback(null, Request(option).
then((data) => {
console.log('IP = ', data);
}).catch((err) => {
console.error(err);
})
);
};
function Request(options) {
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
let body = '';
// console.log('Status:', res.statusCode);
// console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
// console.log('Successfully processed HTTP response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
resolve(body);
});
});
req.on('error', (err) => {
reject(err);
});
req.write('');
req.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment