Created
September 9, 2011 15:46
-
-
Save yyfrankyy/1206561 to your computer and use it in GitHub Desktop.
JSONP Proxy
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
| // vim: set ts=2 sw=2: | |
| var express = require('express'); | |
| var http = require('http'); | |
| var url = require('url'); | |
| var xml2json = require('xml2json'); | |
| var slideshare = require('./slideshare'); | |
| var app = express.createServer(); | |
| function jsonp(key, api, extra, xml) { | |
| app.get('/' + key, function(req, res) { | |
| var params = []; | |
| if (extra) { | |
| var query = extra(); | |
| for (var i in query) { | |
| req.query[i] = query[i]; | |
| } | |
| } | |
| for (var i in req.query) { | |
| params.push([i, req.query[i]].join('=')); | |
| } | |
| api = api.replace(/\?.*/, '') + '?' + params.join('&'); | |
| var uri = url.parse(api); | |
| uri.path = uri.pathname + uri.search; | |
| http.get(uri, function(resp) { | |
| if (res.statusCode == 200) { | |
| var data = ''; | |
| resp.on('data', function(buf) { | |
| data += buf.toString(); | |
| }).on('end', function() { | |
| if (xml) { | |
| data = xml2json.toJson(data); | |
| } | |
| jsonpSend(req, res, data); | |
| }); | |
| } else { | |
| jsonpSend(req, res); | |
| } | |
| }).on('error', function(e) { | |
| console.error(e.message); | |
| jsonpSend(req, res); | |
| }); | |
| }); | |
| } | |
| function jsonpSend(req, res, json) { | |
| if (!json) json = {}; | |
| if (typeof json === 'object') { | |
| json = JSON.stringify(json); | |
| } | |
| if (req.query && | |
| req.query.callback && | |
| json.indexOf(req.query.callback) !== 0) { | |
| json = req.query.callback + '(' + json + ')'; | |
| } | |
| res.send(json); | |
| } | |
| jsonp( | |
| 'reader', | |
| 'https://www.google.com/reader/api/0/stream/contents/user/01369356751882780945/state/com.google/broadcast' | |
| ); | |
| jsonp( | |
| 'twitter', | |
| 'https://api.twitter.com/1/statuses/user_timeline.json' | |
| ); | |
| jsonp( | |
| 'slideshare', | |
| 'http://www.slideshare.net/api/2/get_slideshows_by_user', | |
| slideshare.generateValidationData, | |
| true | |
| ); | |
| app.listen(+process.argv[2] || 80); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment