Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Created September 2, 2018 08:01
Show Gist options
  • Select an option

  • Save SoarLin/3cc22f8745ca6a7d81182332d7d1c6e3 to your computer and use it in GitHub Desktop.

Select an option

Save SoarLin/3cc22f8745ca6a7d81182332d7d1c6e3 to your computer and use it in GitHub Desktop.

Revisions

  1. SoarLin created this gist Sep 2, 2018.
    42 changes: 42 additions & 0 deletions lambda-get-ip.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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();
    });
    }