-
-
Save kyle-mccarthy/505904449c3b154e400a8c8a1cc26ff1 to your computer and use it in GitHub Desktop.
This file contains 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
const uWS = require('uWebSockets.js'); | |
const port = 9001; | |
const app = uWS./*SSL*/App({ | |
}).post('/*', async (res, req) => { | |
/* Note that you cannot read from req after returning from here */ | |
let url = req.getUrl(); | |
res.onAborted(() => { | |
res.aborted = true; | |
}); | |
let jsonData; | |
try { | |
jsonData = await readJson(res); | |
} catch (e) { | |
console.log('Invalid JSON or no data at all!'); | |
res.close(); | |
return; | |
} | |
console.log('Posted to ' + url + ': '); | |
console.log(jsonData); | |
try { | |
console.log(req.getHeader('accept')); | |
} catch (e) { | |
// error will be caught | |
// error reading header Using uWS.HttpRequest past its request handler return is forbidden (it is stack allocated). | |
console.log(`error reading header ${e}`); | |
return; | |
} | |
if (res.aborted) { | |
return; | |
} | |
res.end('Thanks for this json!'); | |
}).listen(port, (token) => { | |
if (token) { | |
console.log('Listening to port ' + port); | |
} else { | |
console.log('Failed to listen to port ' + port); | |
} | |
}); | |
/* Helper function for reading a posted JSON body */ | |
function readJson(res) { | |
let buffer; | |
return new Promise((resolve, reject) => { | |
res.onData((ab, isLast) => { | |
let chunk = Buffer.from(ab); | |
if (isLast) { | |
let json; | |
if (buffer) { | |
try { | |
json = JSON.parse(Buffer.concat([buffer, chunk])); | |
} catch (e) { | |
reject(e); | |
} | |
resolve(json); | |
} else { | |
try { | |
json = JSON.parse(chunk); | |
} catch (e) { | |
reject(e); | |
} | |
resolve(json); | |
} | |
} else { | |
if (buffer) { | |
buffer = Buffer.concat([buffer, chunk]); | |
} else { | |
buffer = Buffer.concat([chunk]); | |
} | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment