Skip to content

Instantly share code, notes, and snippets.

@arlolra
Forked from isaacs/server.js
Created January 28, 2012 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arlolra/1696314 to your computer and use it in GitHub Desktop.
Save arlolra/1696314 to your computer and use it in GitHub Desktop.
// test with:
// curl -X POST -d '{ "to" : "isaacs", "from" : "arlolra", "body" : "emoji 🍨 🍩 🍪"}' http://127.0.0.1:1337
var http = require("http")
// messages should be relatively short.
var maxLength = 1024
var server = http.createServer(function (req, res) {
// requests come in as json
// need to parse the json to get from, to, and body fields.
// JSON is probably generated by some native C JSON encoder
// on a device, or in some other language, or perhaps from
// another node program (in which case, it'll already be broken).
var chunks = []
var msgLen = 0
req.on("data", onData)
req.on("end", onEnd)
function onData (chunk) {
chunks.push(chunk)
msgLen += chunk.length
if (msgLen > maxLength) {
// DoS protection.
res.writeHead(413, {"content-type":"application/json"})
res.end(JSON.stringify({ok: false, error: "Request entity too large"}))
req.removeListener("data", onData)
req.removeListener("end", onEnd)
}
}
function onEnd () {
var message
switch (chunks.length) {
case 0: message = new Buffer(0); break
case 1: message = chunks[0]; break
default:
message = new Buffer(msgLen)
var i = 0
chunks.forEach(function (c) {
c.copy(message, i)
i += c.length
})
break
}
var i = 0, code = ''
for (; i < msgLen; i++) {
code += String.fromCharCode(message[i])
}
// so, now message is the full message
// it's a buffer, but we need to interpret it as JSON
// this is where the Bad Thing happens.
// if there were any characters outside the 2-byte plane,
// then they're going to now get turned into 2 garbage characters.
try {
message = JSON.parse(code)
} catch (ex) {
console.error(ex)
res.writeHead(400, {"content-type":"application/json"})
res.end(JSON.stringify({ok:false, error:"Bad JSON"}))
return
}
// in real life, this console.error would be replaced with
// some nifty routing message passing thingie
// console.error("From: %s\nTo: %s\n\n%s",
// message.from, message.to, message.body);
var mb = message.body
, len = mb.length
, buf = new Buffer(len + 1)
for (i = 0; i < len; i++) {
buf[i] = mb.charCodeAt(i)
}
buf[i] = 10
process.stdout.write(buf)
res.writeHead(200, { "content-type": "application/json" })
res.end(JSON.stringify({ ok: true }) + "\n")
}
})
server.listen(1337)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment