3 var http = require('http');
5 var port = parseInt(process.env.PORT || 8000);
7 var fixed = makeString(20 * 1024, 'C'),
12 var useDomains = process.env.NODE_USE_DOMAINS;
14 // set up one global domain.
16 var domain = require('domain');
17 var gdom = domain.create();
18 gdom.on('error', function(er) {
19 console.error('Error on global domain', er);
25 var server = module.exports = http.createServer(function(req, res) {
27 var dom = domain.create();
32 var commands = req.url.split('/');
33 var command = commands[1];
35 var arg = commands[2];
36 var n_chunks = parseInt(commands[3], 10);
39 if (command == 'bytes') {
42 throw new Error('bytes called with n <= 0');
43 if (storedBytes[n] === undefined) {
44 storedBytes[n] = makeString(n, 'C');
46 body = storedBytes[n];
48 } else if (command == 'buffer') {
51 throw new Error('buffer called with n <= 0');
52 if (storedBuffer[n] === undefined) {
53 storedBuffer[n] = new Buffer(n);
54 for (var i = 0; i < n; i++) {
55 storedBuffer[n][i] = 'C'.charCodeAt(0);
58 body = storedBuffer[n];
60 } else if (command == 'unicode') {
63 throw new Error('unicode called with n <= 0');
64 if (storedUnicode[n] === undefined) {
65 storedUnicode[n] = makeString(n, '\u263A');
67 body = storedUnicode[n];
69 } else if (command == 'quit') {
70 res.connection.server.close();
73 } else if (command == 'fixed') {
76 } else if (command == 'echo') {
77 res.writeHead(200, { 'Content-Type': 'text/plain',
78 'Transfer-Encoding': 'chunked' });
87 // example: http://localhost:port/bytes/512/4
88 // sends a 512 byte body in 4 chunks of 128 bytes
90 res.writeHead(status, { 'Content-Type': 'text/plain',
91 'Transfer-Encoding': 'chunked' });
92 // send body in chunks
93 var len = body.length;
94 var step = Math.floor(len / n_chunks) || 1;
96 for (var i = 0, n = (n_chunks - 1); i < n; ++i) {
97 res.write(body.slice(i * step, i * step + step));
99 res.end(body.slice((n_chunks - 1) * step));
101 var content_length = body.length.toString();
103 res.writeHead(status, { 'Content-Type': 'text/plain',
104 'Content-Length': content_length });
109 function makeString(size, c) {
111 while (s.length < size) {
117 server.listen(port, function() {
118 if (module === require.main)
119 console.error('Listening at http://127.0.0.1:' + port + '/');