-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpsink
executable file
·98 lines (81 loc) · 1.94 KB
/
httpsink
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env node
'use strict';
const { Server } = require('http');
//
// HELPERS
//
function capital(word) {
return word.charAt(0).toUpperCase() + word.substring(1);
}
function fmt(code, text) {
return `\x1b[${code}m${text}\x1b[0m`;
}
const colors = {
black: '30',
red: '31',
green: '32',
yellow: '33',
blue: '34',
magenta: '35',
cyan: '36',
grey: '90',
white: '97',
};
Object.keys(colors).forEach(function (color) {
fmt[color] = text => fmt(colors[color], text);
});
//
// IMPLEMENTATION
//
const server = new Server();
let tries = 1;
server.on('listening', function () {
const port = this.address().port;
console.log(`server listening on port ${fmt.blue(port)}\n`);
});
server.on('error', function (e) {
if (e.code === 'EADDRINUSE' && tries <= 10) {
console.log(
`${fmt.yellow('warning')}: port ${fmt.yellow(e.port)} is in use, trying ${
e.port + 1
}`
);
server.listen(++e.port);
tries++;
} else {
throw e;
}
});
server.on('request', (req, res) => {
console.log(
`${fmt.magenta(req.method)} ${fmt.grey(req.url)} HTTP/${req.httpVersion}`
);
Object.keys(req.headers).forEach(function (header) {
console.log(
`${fmt.grey(capital(header))}: ${fmt.blue(req.headers[header])}`
);
});
console.log();
let body = [];
req
.on('data', ch => body.push(ch))
.on('end', function () {
body = Buffer.concat(body).toString();
if (req.headers['content-type'] == 'application/json') {
console.log(JSON.stringify(JSON.parse(body), null, 2));
} else {
console.log(body);
}
console.log();
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
}
res.writeHead(200);
res.end();
});
});
server.listen(process.env.PORT || 4000);