Created
September 2, 2018 08:01
-
-
Save SoarLin/3cc22f8745ca6a7d81182332d7d1c6e3 to your computer and use it in GitHub Desktop.
AWS Lambda Function to Get Internet IP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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