Skip to content

Instantly share code, notes, and snippets.

@JuninhoFreitas
Created May 9, 2023 13:39
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 JuninhoFreitas/d7a6ef58c45149d62dd0025951d96bc1 to your computer and use it in GitHub Desktop.
Save JuninhoFreitas/d7a6ef58c45149d62dd0025951d96bc1 to your computer and use it in GitHub Desktop.
An endpoint just to return what u have sent, using only native features.
const http = require('http');
const port = 3349
const routes = {
'/': handlePostReq
}
const server = http.createServer((req, res) => {
routes[req.url](req, res);
})
function handlePostReq(req, res) {
const size = parseInt(req.headers['content-length'], 10)
const buffer = Buffer.allocUnsafe(size)
var pos = 0
req.on('data', (chunk) => {
const offset = pos + chunk.length
if (offset > size) {
reject(413, 'Too Large', res)
return
}
chunk.copy(buffer, pos)
pos = offset
})
.on('end', () => {
if (pos !== size) {
reject(400, 'Bad Request', res)
return
}
const data = JSON.parse(buffer.toString())
res.setHeader('Content-Type', 'application/json;charset=utf-8');
res.end(JSON.stringify(data))
})
}
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment