AlexanderMac / http-z

Parse/build HTTP message to/from model
MIT License
18 stars 6 forks source link

http-z

HTTP message (request/response) parser/builder according to the rules defined in RFC 7230

Works in Node.js and in the browser.

Build Status Code Coverage License npm version

Demo

Install

$ pnpm i http-z

Usage

const httpZ = require('http-z')

const plainMessage = [
  'GET /features?p1=v1 HTTP/1.1',
  'Host: example.com',
  'Accept: *',
  'Accept-Encoding: gzip,deflate',
  'Accept-Language: en-US;q=0.6, en;q=0.4',
  '',
  ''
].join('\r\n')

const messageModel = httpZ.parse(plainMessage)
console.log(JSON.stringify(messageModel, null, 2))

/* output:
{
  "protocolVersion": "HTTP/1.1",
  "method": "GET",
  "target": "/features?p1=v1",
  "host": "example.com",
  "path": "/features",
  "headersSize": 135,
  "bodySize": 0,
  "queryParams": [
    { "name": "p1", "value": "v1" }
  ],
  "headers": [
    { "name": "Host", "value": "example.com" },
    { "name": "Accept", value": "*" },
    { "name": "Accept-Encoding", "value": "gzip,deflate" },
    { "name": "Accept-Language", "value": "en-US;q=0.6, en;q=0.4" }
  ]
}
*/

const plainMessageParsed = httpZ.build(messageModel)
console.log(plainMessageParsed)

/* output:
GET /features?p1=v1 HTTP/1.1
Host: example.com
Accept: *
Accept-Encoding: gzip,deflate
Accept-Language: en-US;q=0.6, en;q=0.4

*/

API

parse(rawMessage, opts)

Parses HTTP request/response raw message and returns a model.

build(messageModel, opts)

Builds HTTP request/response raw message from the model.

References

License

Licensed under the MIT license.

Author

Alexander Mac