parseHeaders.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var utils = require('./../utils');
  3. // Headers whose duplicates are ignored by node
  4. // c.f. https://nodejs.org/api/http.html#http_message_headers
  5. var ignoreDuplicateOf = [
  6. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  7. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  8. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  9. 'referer', 'retry-after', 'user-agent'
  10. ];
  11. /**
  12. * Parse headers into an object
  13. *
  14. * ```
  15. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  16. * Content-Type: application/json
  17. * Connection: keep-alive
  18. * Transfer-Encoding: chunked
  19. * ```
  20. *
  21. * @param {String} headers Headers needing to be parsed
  22. * @returns {Object} Headers parsed into an object
  23. */
  24. module.exports = function parseHeaders(headers) {
  25. var parsed = {};
  26. var key;
  27. var val;
  28. var i;
  29. if (!headers) { return parsed; }
  30. utils.forEach(headers.split('\n'), function parser(line) {
  31. i = line.indexOf(':');
  32. key = utils.trim(line.substr(0, i)).toLowerCase();
  33. val = utils.trim(line.substr(i + 1));
  34. if (key) {
  35. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  36. return;
  37. }
  38. if (key === 'set-cookie') {
  39. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  40. } else {
  41. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  42. }
  43. }
  44. });
  45. return parsed;
  46. };