Skip to content

Instantly share code, notes, and snippets.

@stephenquan
Last active April 18, 2018 00:32
Show Gist options
  • Save stephenquan/913048976dd01617ce3d92ca3b34e552 to your computer and use it in GitHub Desktop.
Save stephenquan/913048976dd01617ce3d92ca3b34e552 to your computer and use it in GitHub Desktop.
node-https.js
module.exports = {
port: 8080,
createOptions: {
name: 'Http Server',
version: '1.0.0'
},
bodyParserOptions: {
uploadDir: '/tmp/node_https',
keepExtensions: true
}
}
// HTTPS Node.js restify request service
var config = require('./node-https-config');
var fs = require('fs');
var restify = require('restify');
var request = require('request');
if (config.bodyParserOptions) {
if (!fs.existsSync(config.bodyParserOptions.uploadDir)) {
fs.mkdirSync(config.bodyParserOptions.uploadDir);
}
}
var server = restify.createServer(config.createOptions || { });
server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser(config.bodyParserOptions || { }));
server.post('/https/*', httpsRequest);
server.get('/https/*', httpsRequest);
server.listen(config.port || 8080, () => {
console.log('%s listening at %s', server.name, server.url);
} );
function sendResponse(req, res, next, data, dataType, statusCode) {
if (req.params && req.params.callback) {
res.send(data);
next();
return;
}
if (data instanceof Object) {
if (req.params && req.params.f == 'pjson') {
data = JSON.stringify(data, undefined, 2) + "\n";
dataType = 'text/plain';
} else {
data = JSON.stringify(data);
dataType = 'text/plain';
}
}
if (typeof data === 'string') {
res.set( {
'Content-Length': Buffer.byteLength(data),
'Content-Type': dataType || 'text/plain'
} );
res.send(statusCode || 200, data);
next();
return;
}
res.send(data);
next();
}
function httpsRequest(req, res, next) {
console.log(new Date(), req.method, req.url);
var m = req.url.match(/^\/https\/(.*)/);
var obj = {
uri: "https://" + m[1],
method: req.method,
headers: { }
};
for (var h in req.headers) {
switch (h) {
case 'host':
case 'content-length':
case 'content-type':
continue;
}
req.headers[h] = req.headers[h];
}
if (req.body) {
obj.form = req.body;
}
if (req.files) {
if (!obj.form) obj.form = { };
for (var f in req.files) {
var file = req.files[f];
obj.form[f] = {
value: fs.readFileSync(file.path),
options: {
filename: file.name,
contentType: file.type
}
}
}
}
request(obj, function (err, resp, body) {
if (err) {
console.log(err);
sendResponse(req, res, next, err, undefined, 200);
return;
}
sendResponse(req, res, next, body, undefined, resp.statusCode);
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment