All Projects → szmarczak → Http2 Wrapper

szmarczak / Http2 Wrapper

Licence: mit
Use HTTP2 the same way like HTTP1

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Http2 Wrapper

Piaf
Client library for HTTP/1.X / HTTP/2 written entirely in OCaml.
Stars: ✭ 86 (-53.01%)
Mutual labels:  http2, https
Ymhttp
基于 libcurl 的 IO 多路复用 HTTP 框架,适用于 iOS 平台,支持 HTTP/HTTPS/HTTP2/DNS(SNI)
Stars: ✭ 127 (-30.6%)
Mutual labels:  http2, https
Serve
Simple http server for localhost development with a flags for enabling gzip and http2
Stars: ✭ 93 (-49.18%)
Mutual labels:  http2, https
Katwebx
An extremely fast static web server and reverse proxy for the modern web.
Stars: ✭ 39 (-78.69%)
Mutual labels:  http2, https
Siris
DEPRECATED: The community driven fork of Iris. The fastest web framework for Golang!
Stars: ✭ 146 (-20.22%)
Mutual labels:  http2, https
Esa Restlight
ESA Restlight is a lightweight and rest-oriented web framework.
Stars: ✭ 67 (-63.39%)
Mutual labels:  http2, https
Https Localhost
HTTPS server running on localhost
Stars: ✭ 122 (-33.33%)
Mutual labels:  http2, https
Farwest
Framework for building RESTful HATEOAS-driven applications.
Stars: ✭ 18 (-90.16%)
Mutual labels:  http2, https
Nuster
A high performance HTTP proxy cache server and RESTful NoSQL cache server based on HAProxy
Stars: ✭ 1,825 (+897.27%)
Mutual labels:  http2, https
Httpserver
Http server is written on C++14 language. Dynamic libraries act as applications for the server (*.so - linux, *.dll - windows).
Stars: ✭ 141 (-22.95%)
Mutual labels:  http2, https
Xmnetworking
A lightweight but powerful network library with simplified and expressive syntax based on AFNetworking.
Stars: ✭ 980 (+435.52%)
Mutual labels:  http2, https
Nginxconfig.io
⚙️ NGINX config generator on steroids 💉
Stars: ✭ 14,983 (+8087.43%)
Mutual labels:  http2, https
Shgf
Simple HTTP golang framework
Stars: ✭ 13 (-92.9%)
Mutual labels:  http2, https
Okurl
OkHttp Kotlin command line
Stars: ✭ 77 (-57.92%)
Mutual labels:  http2, https
Golang Tls
Simple Golang HTTPS/TLS Examples
Stars: ✭ 857 (+368.31%)
Mutual labels:  http2, https
X0
Xzero HTTP Application Server
Stars: ✭ 111 (-39.34%)
Mutual labels:  http2, https
Symfony Docker
A Docker-based installer and runtime for Symfony. Install: download and `docker-compose up`.
Stars: ✭ 732 (+300%)
Mutual labels:  http2, https
Cowboy
Small, fast, modern HTTP server for Erlang/OTP.
Stars: ✭ 6,533 (+3469.95%)
Mutual labels:  http2, https
Armor
Uncomplicated, modern HTTP server
Stars: ✭ 1,629 (+790.16%)
Mutual labels:  http2, https
Awesome Http Benchmark
HTTP(S) benchmark tools, testing/debugging, & restAPI (RESTful)
Stars: ✭ 2,236 (+1121.86%)
Mutual labels:  http2, https

http2-wrapper

HTTP/2 client, just with the familiar https API

Node CI codecov npm install size

This package was created to support HTTP/2 without the need to rewrite your code.
I recommend adapting to the http2 module if possible - it's much simpler to use and has many cool features!

Tip: http2-wrapper is very useful when you rely on other modules that use the HTTP/1 API and you want to support HTTP/2.

Pro Tip: While the native http2 doesn't have agents yet, you can use http2-wrapper Agents and still operate on the native HTTP/2 streams.

Installation

$ npm install http2-wrapper
$ yarn add http2-wrapper

Usage

const http2 = require('http2-wrapper');

const options = {
	hostname: 'nghttp2.org',
	protocol: 'https:',
	path: '/httpbin/post',
	method: 'POST',
	headers: {
		'content-length': 6
	}
};

const request = http2.request(options, response => {
	console.log('statusCode:', response.statusCode);
	console.log('headers:', response.headers);

	const body = [];
	response.on('data', chunk => {
		body.push(chunk);
	});
	response.on('end', () => {
		console.log('body:', Buffer.concat(body).toString());
	});
});

request.on('error', console.error);

request.write('123');
request.end('456');

// statusCode: 200
// headers: [Object: null prototype] {
//   ':status': 200,
//   date: 'Fri, 27 Sep 2019 19:45:46 GMT',
//   'content-type': 'application/json',
//   'access-control-allow-origin': '*',
//   'access-control-allow-credentials': 'true',
//   'content-length': '239',
//   'x-backend-header-rtt': '0.002516',
//   'strict-transport-security': 'max-age=31536000',
//   server: 'nghttpx',
//   via: '1.1 nghttpx',
//   'alt-svc': 'h3-23=":4433"; ma=3600',
//   'x-frame-options': 'SAMEORIGIN',
//   'x-xss-protection': '1; mode=block',
//   'x-content-type-options': 'nosniff'
// }
// body: {
//   "args": {},
//   "data": "123456",
//   "files": {},
//   "form": {},
//   "headers": {
//     "Content-Length": "6",
//     "Host": "nghttp2.org"
//   },
//   "json": 123456,
//   "origin": "xxx.xxx.xxx.xxx",
//   "url": "https://nghttp2.org/httpbin/post"
// }

API

Note: The session option was renamed to tlsSession for better readability.

http2.auto(url, options, callback)

Performs ALPN negotiation. Returns a Promise giving proper ClientRequest instance (depending on the ALPN).

Note: The agent option represents an object with http, https and http2 properties.

const http2 = require('http2-wrapper');

const options = {
	hostname: 'httpbin.org',
	protocol: 'http:', // Try changing this to https:
	path: '/post',
	method: 'POST',
	headers: {
		'content-length': 6
	}
};

(async () => {
	try {
		const request = await http2.auto(options, response => {
			console.log('statusCode:', response.statusCode);
			console.log('headers:', response.headers);

			const body = [];
			response.on('data', chunk => body.push(chunk));
			response.on('end', () => {
				console.log('body:', Buffer.concat(body).toString());
			});
		});

		request.on('error', console.error);

		request.write('123');
		request.end('456');
	} catch (error) {
		console.error(error);
	}
})();

// statusCode: 200
// headers: { connection: 'close',
//   server: 'gunicorn/19.9.0',
//   date: 'Sat, 15 Dec 2018 18:19:32 GMT',
//   'content-type': 'application/json',
//   'content-length': '259',
//   'access-control-allow-origin': '*',
//   'access-control-allow-credentials': 'true',
//   via: '1.1 vegur' }
// body: {
//   "args": {},
//   "data": "123456",
//   "files": {},
//   "form": {},
//   "headers": {
//     "Connection": "close",
//     "Content-Length": "6",
//     "Host": "httpbin.org"
//   },
//   "json": 123456,
//   "origin": "xxx.xxx.xxx.xxx",
//   "url": "http://httpbin.org/post"
// }

http2.auto.protocolCache

An instance of quick-lru used for ALPN cache.

There is a maximum of 100 entries. You can modify the limit through protocolCache.maxSize - note that the change will be visible globally.

http2.request(url, options, callback)

Same as https.request.

options.h2session

Type: Http2Session

The session used to make the actual request. If none provided, it will use options.agent to get one.

http2.get(url, options, callback)

Same as https.get.

new http2.ClientRequest(url, options, callback)

Same as https.ClientRequest.

new http2.IncomingMessage(socket)

Same as https.IncomingMessage.

new http2.Agent(options)

Note: this is not compatible with the classic http.Agent.

Usage example:

const http2 = require('http2-wrapper');

class MyAgent extends http2.Agent {
	createConnection(origin, options) {
		console.log(`Connecting to ${http2.Agent.normalizeOrigin(origin)}`);
		return http2.Agent.connect(origin, options);
	}
}

http2.get({
	hostname: 'google.com',
	agent: new MyAgent()
}, response => {
	response.on('data', chunk => console.log(`Received chunk of ${chunk.length} bytes`));
});

options

Each option is an Agent property and can be changed later.

timeout

Type: number
Default: 0

If there's no activity after timeout milliseconds, the session will be closed. If 0, no timeout is applied.

maxSessions

Type: number
Default: Infinity

The maximum amount of sessions in total.

maxEmptySessions

Type: number
Default: 10

The maximum amount of empty sessions in total. An empty session is a session with no pending requests.

maxCachedTlsSessions

Type: number
Default: 100

The maximum amount of cached TLS sessions.

agent.protocol

Type: string
Default: https:

agent.settings

Type: object
Default: {enablePush: false}

Settings used by the current agent instance.

agent.normalizeOptions(options)

Returns a string representing normalized options.

Agent.normalizeOptions({servername: 'example.com'});
// => ':::::::::::::::::::::::::::::::::::::'

agent.getSession(origin, options)

origin

Type: string URL object

Origin used to create new session.

options

Type: object

Options used to create new session.

Returns a Promise giving free Http2Session. If no free sessions are found, a new one is created.

A session is considered free when pending streams count is less than max concurrent streams settings.

agent.getSession(origin, options, listener)

listener

Type: object

{
	reject: error => void,
	resolve: session => void
}

If the listener argument is present, the Promise will resolve immediately. It will use the resolve function to pass the session.

agent.request(origin, options, headers, streamOptions)

Returns a Promise giving Http2Stream.

agent.createConnection(origin, options)

Returns a new TLSSocket. It defaults to Agent.connect(origin, options).

agent.closeEmptySessions(count)

count

Type: number Default: Number.POSITIVE_INFINITY

Makes an attempt to close empty sessions. Only sessions with 0 concurrent streams will be closed.

agent.destroy(reason)

Destroys all sessions.

agent.emptySessionCount

Type: number

A number of empty sessions.

agent.pendingSessionCount

Type: number

A number of pending sessions.

agent.sessionCount

Type: number

A number of all sessions held by the Agent.

Event: 'session'

agent.on('session', session => {
	// A new session has been created by the Agent.
});

Proxy support

Currently http2-wrapper provides support for these proxies:

  • HttpOverHttp2
  • HttpsOverHttp2
  • Http2OverHttp2
  • Http2OverHttp
  • Http2OverHttps

Any of the above can be accessed via http2wrapper.proxies. Check out the examples/proxies directory to learn more.

Mirroring another server

See examples/proxies/mirror.js for an example.

WebSockets over HTTP/2

See examples/ws for an example.

Push streams

See examples/push-stream for an example.

Related

  • got - Simplified HTTP requests
  • http2-proxy - A simple http/2 & http/1.1 spec compliant proxy helper for Node.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].