public
Created

  • Download Gist
push_proxy.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
String.prototype.getBytes = function() {
return encodeURIComponent(this).replace(/%../g, 'x').length;
};
 
var puts = require("sys").puts,
http = require("http"),
server = http.createServer,
pubClient = http.createClient(80, "localhost");
 
var postServer = server(function (postRequest, postResponse) {
var uri = postRequest.uri,
path = uri.path,
params = uri.params,
pubRequest = false;
 
puts("uri: " + JSON.stringify(uri));
 
var invalid = (postRequest.method != "POST");
invalid = invalid || (path != '/messages/post/1');
 
var message = '';
postRequest.setBodyEncoding('utf8');
postRequest.addListener('body', function (chunk) {
message += chunk;
});
 
postRequest.connection.addListener('close', function () {
puts("Connection reset by remote peer!");
});
 
postRequest.addListener('complete', function () {
//At this stage we have all the data, so we can persist
var messageByteLength = message.getBytes();
invalid = invalid || (messageByteLength == 0);
if (!invalid) {
puts("Got post message: [1] - " + message);
 
var pubRequestHeaders = {
"host": 'bootstrip.localhost',
"content-type": 'application/json',
"content-length": messageByteLength,
"user-agent": 'node.js http client'
};
 
//Publish to NHPM
pubRequest = pubClient.request("POST", "/messages/pub?id=1", pubRequestHeaders);
pubRequest.sendBody(message, "utf8");
pubRequest.finish(function (pubResponse) {
 
pubResponse.setBodyEncoding("utf8");
 
var pubResponseContent = '';
pubResponse.addListener("body", function (chunk) {
pubResponseContent += chunk;
});
 
pubResponse.addListener("complete", function () {
puts "[NHPM] " + pubResponseContent;
});
 
postResponse.sendHeader(200, {
"Content-Length": 0,
"Content-Type": "text/plain"
});
postResponse.finish();
});
 
} else {
puts("Invalid message!");
postResponse.sendHeader(500, {
"Content-Length": 0,
"Content-Type": "text/plain"
});
postResponse.finish();
};
});
});
 
postServer.listen(8080, 'localhost');

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.