Skip to content

Instantly share code, notes, and snippets.

@triblondon
Last active December 3, 2018 19:13
Show Gist options
  • Save triblondon/ea0d59e367af015021738f382a4de98c to your computer and use it in GitHub Desktop.
Save triblondon/ea0d59e367af015021738f382a4de98c to your computer and use it in GitHub Desktop.
PEG parser for HTTP Structured headers
expression "expression" =
first:param rest:(OWS FIELD_SEP OWS param)* {
return [first]
.concat(rest.map(entry => entry[3]))
.reduce((obj, entry) => Object.assign(obj, {[entry.label]: entry.value}), {})
}
param "param" =
label:label val:(OWS "=" OWS (number / label / string))? {
const op = { type: 'param', label: label.value };
if (val) {
op.value = val[3].value;
op.valType = val[3].type;
}
return op;
}
string "string" =
DQUOTE text:(doublequoted_character*) DQUOTE {
return { type: 'string', value: text.join('') };
}
label = text:( [a-z] / DIGIT / "_" / "-" / "*" / "/" )+ {
return { type: 'label', value: text.join('') };
}
number = val:([0-9\.\-]+) {
return { type: 'number', value: Number.parseFloat(val.join(''), 10) };
}
character = unescaped / escape_sequence
escape_sequence =
ESC_CHAR val:( DQUOTE / ESC_CHAR ) { return val; }
doublequoted_character =
(!DQUOTE) c:character { return c; }
OWS "whitespace" = [ \t]*
ESC_CHAR = "\\"
DQUOTE "double quote" = '"'
unescaped = [\x20-\x21] / [\x23-\x5B] / [\x5D-\x7E]
HEX_DIG = [0-9a-f]i
DIGIT = [0-9]
FIELD_SEP = [,;]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment