Mostra notizie nelle discussioni
Avatar
☺
Scritto da
::1
il 2013-11-10 21:34:18.0 alle 2013-11-10 21:34:18.0
Trollate totali: 12321
[nodejs] @altg: aggiungere un header a tutte le response
Ho scritto questa cosina stasera, magari ti serve:
var http = require('http');

var writeHead = http.ServerResponse.prototype.writeHead;
http.ServerResponse.prototype.writeHead = function() {
  // response.writeHead(statusCode, [reasonPhrase], [headers])
  var headers =
    arguments[1] && typeof arguments[1] === 'object'
      ? arguments[1]
      : arguments[2] && typeof arguments[2] === 'object'
        ? arguments[2]
        : null;
  if (headers) {
    headers['Server'] = 'proott';
    writeHead.apply(this, arguments);
  } else {
    headers = {};
    headers['Server'] = 'proott';
    writeHead.apply(this, Array.prototype.slice.call(arguments).concat([headers]));
  }
  this.writeHeadWasCalled = true;
}

var end = http.ServerResponse.prototype.end;
http.ServerResponse.prototype.end = function() {
  // response.end([data], [encoding])
  if (!this.writeHeadWasCalled) {
    this.writeHead(200, {'Server' : 'proott'});
  }
  end.apply(this, arguments);
}

var server = http.createServer(function(req, res) {
  if (req.url === '/writeHeadWithHeaders') {
    res.writeHead(200, {'Content-Type' : 'text/plain'});
  } else if (req.url === '/writeHeadWithoutHeaders') {
    res.writeHead(200);
  }
  res.end('ok')
});

server.listen(8080);


I test:
$ echo -n 'GET / HTTP/1.0\r\n\r\n' | nc localhost 8080
HTTP/1.1 200 OK
Server: proott
Date: Sun, 10 Nov 2013 20:32:11 GMT
Connection: close

ok
$ echo -n 'GET /writeHeadWithHeaders HTTP/1.0\r\n\r\n' | nc localhost 8080
HTTP/1.1 200 OK
Content-Type: text/plain
Server: proott
Date: Sun, 10 Nov 2013 20:32:48 GMT
Connection: close

ok
$ echo -n 'GET /writeHeadWithoutHeaders HTTP/1.0\r\n\r\n' | nc localhost 8080
HTTP/1.1 200 OK
Server: proott
Date: Sun, 10 Nov 2013 20:33:11 GMT
Connection: close

ok
Young professional woman and busy mom.

Pagina generata in 72 millisecondi

Utenti attivi: 12 nell'ultimo minuto, 25 negli ultimi cinque minuti, 40 negli ultimi 15 minuti