Skip to content

Instantly share code, notes, and snippets.

@kerrishotts
Created October 5, 2014 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerrishotts/67a077893f6223f42758 to your computer and use it in GitHub Desktop.
Save kerrishotts/67a077893f6223f42758 to your computer and use it in GitHub Desktop.
Parse Response Headers
/**
*
* Parse response header string of the form:
*
* "
* header: value
* another-header: value
* "
*
* @param {string} headerStr headers to parse
* @param {boolean} modifyKeys if true, header keys are modified to be
* camelcase. default: true
* @return {*} object containing header keys
*
*/
function parseResponseHeaders( headerStr, modifyKeys ) {
// no header? return an empty object
if ( !headerStr ) {
return {};
}
// check if modifyKeys is passed; if not true is the default
if ( typeof modifyKeys === "undefined" ) {
modifyKeys = true;
}
// split the header string by carraige return, then reduce it to
// an object containing the header keys and values
return headerStr.split( "\r\n" ).reduce(
function parseHeader( prevValue, headerPair ) {
// header is of the form abc: def; split by ": " and then
// shift out the key. Reconstruct the value in case some one has
// a header of abc: def: ghi
var headerParts = headerPair.split( ": " ),
headerKey = headerParts.shift(),
headerValue = headerParts.join( ": " ),
propParts, prop;
if ( modifyKeys ) {
// convert some-property-key to somePropertyKey
propParts = headerKey.split( "-" );
prop = propParts.reduce( function ( prevValue, v ) {
return prevValue + ( v.substr( 0, 1 ).toUpperCase() + v.substr( 1 ) );
} );
prop = prop.substr( 0, 1 ).toLowerCase() +
prop.substr( 1 );
}
// if we have one or more part, copy the value to the key
if ( headerParts.length > 0 ) {
prevValue[ modifyKeys ? prop : headerKey ] = headerValue;
} else {
// otherwise just copy true
prevValue[ modifyKeys ? prop : headerKey ] = true;
}
return prevValue;
}, {} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment