Skip to content

Instantly share code, notes, and snippets.

@s-aska
Created April 26, 2016 07:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save s-aska/09fccff1acac5cdad474b2195b048d60 to your computer and use it in GitHub Desktop.
OGP Fetch API for AWS Lambda
'use strict';
console.log('Loading function');
const http = require('http');
const https = require('https');
const regexs = [
new RegExp('<meta property=["\']og:title["\'] content=["\']([^>]+)["\']', 'i'),
new RegExp('<meta content=["\']([^>]+)["\'] property=["\']og:title["\']', 'i'),
new RegExp('<title>([^<]*)</title>', 'i'),
];
exports.handler = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
const url = event.url;
const module = url.indexOf('https://') !== -1 ? https : http;
module.get(url, function(res) {
var body = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
for (var i = 0; i < regexs.length; i ++) {
var regex = regexs[i];
var match = regex.exec(body);
if (match && match[1]) {
callback(null, {"url": url, "title": match[1]});
return
}
}
callback(null, {"url": url, "title": ""});
});
}).on('error', function(e) {
callback(null, {"url": url, "title": "", "error": e.message});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment