Created
December 26, 2018 00:59
-
-
Save pietermees/cb9d8cc69e4c6bf05499aa8e1e6426c5 to your computer and use it in GitHub Desktop.
Using got with alpn-agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ALPNAgent = require('@zentrick/alpn-agent') | |
const { Agent: HttpAgent } = require('http') | |
const http2 = require('http2-wrapper') | |
const { extend: gotExtend } = require('got') | |
const got = gotExtend({ | |
hooks: { | |
beforeRequest: [ | |
async options => { | |
if (options.request != null) { | |
// Use request function provided by options | |
return | |
} | |
if (!(options.agent instanceof ALPNAgent)) { | |
// Don't use ALPN negotiation | |
return | |
} | |
if (options.protocol !== 'https:') { | |
// Not using HTTPS | |
return | |
} | |
const alpnProto = await options.agent.negotiateALPN(options) | |
if (alpnProto === 'h2') { | |
options.socketSession = options.session | |
options.session = await options.agent.createH2Session(options) | |
options.request = http2.request | |
} | |
} | |
] | |
} | |
}) | |
const alpnAgent = new ALPNAgent() | |
const httpAgent = new HttpAgent() | |
const runTest = async (name, url, options = null) => { | |
const { body } = await got( | |
url, | |
Object.assign({}, options, { | |
json: true, | |
agent: url.startsWith('https://') ? alpnAgent : httpAgent | |
}) | |
) | |
console.log(name, body) | |
} | |
const runTests = async () => { | |
await runTest('http2-alpn', 'https://nghttp2.org/httpbin/headers') | |
await runTest('http2-h1', 'https://nghttp2.org/httpbin/headers', { | |
ALPNProtocols: ['http/1.1'] | |
}) | |
await runTest('https-alpn', 'https://httpbin.org/headers') | |
await runTest('http', 'http://httpbin.org/headers') | |
await alpnAgent.destroy() | |
} | |
runTests() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment