Skip to content

Instantly share code, notes, and snippets.

@ezekg
Created July 6, 2022 16:57
Show Gist options
  • Save ezekg/6a9da04711b1b28d15e8b74ed8e436f8 to your computer and use it in GitHub Desktop.
Save ezekg/6a9da04711b1b28d15e8b74ed8e436f8 to your computer and use it in GitHub Desktop.
How to quickly parse a parameterized HTTP header, such as Cookie or Signature, using Node.
const header = `keyid="bf9b523f-dd65-48a2-9512-fb66ba6c3714",
algorithm="ed25519",
signature="KhgcM+Ywv+DnQj4gE+DqWfNTM2TG5wfRuFQZ/zW48ValZuCHEu1h95Uyldqe7I85sS/QliCiRAF5QfW8ZN2vAw==",
headers="(request-target) host date digest"`
// Parse the parameterized header into an object
const params = header.split(/,\s*/g)
.map(keyvalue => keyvalue.match(/(?<key>[^=]+)="(?<value>[^"]+)"/i))
.map(matches => matches.groups)
.reduce(
(obj, { key, value }) => (obj[key] = value, obj),
{},
)
console.log({ params })
// => {
// params: {
// keyid: 'bf9b523f-dd65-48a2-9512-fb66ba6c3714',
// algorithm: 'ed25519',
// signature: 'KhgcM+Ywv+DnQj4gE+DqWfNTM2TG5wfRuFQZ/zW48ValZuCHEu1h95Uyldqe7I85sS/QliCiRAF5QfW8ZN2vAw==',
// headers: '(request-target) host date digest'
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment