-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
68 lines (55 loc) · 1.32 KB
/
index.js
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
"use strict";
// Imports
const express = require("express");
const app = express();
// Constants
const PORT = process.env.HTTP_ECHO_PORT || 80;
const HOST = process.env.HTTP_ECHO_HOST || "0.0.0.0";
const CNTLEN_HEADER = "content-length";
/**
* Parses body and calls callback handle with value
* @param {*} req Express request
* @param {*} callback Callback that takes body string argument
*/
function readBodyAsString(req, callback) {
let eof = +req.headers[CNTLEN_HEADER];
if (isNaN(eof)) {
callback(null);
}
let body = "";
if (eof === 0) {
callback(body);
}
req.on("data", (chunk) => {
body += chunk.toString();
if(eof === body.length) {
callback(body);
}
});
}
/** Defining requests handling */
app.all("*", (req, res) => {
readBodyAsString(req, (body) => {
res.json(
{
date: new Date().toJSON(),
method: req.method,
path: req.path,
headers: req.headers,
body: body,
query: req.query
}
);
});
});
// Starts Express http listener
app.listen(
PORT,
HOST,
() =>
{
console.log(
`Http-echo is now running on http://${HOST}:${PORT}`
);
}
);