Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add http2 support #2

Merged
merged 1 commit into from
Feb 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 53 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ module.exports = fp(function from (fastify, opts, next) {
const url = cache.get(source) || new URL(source, base)
cache.set(source, url)

var headers = req.headers
const isHttp2 = req.httpVersionMajor === 2
var headers = isHttp2 ? http2toHttp1Headers(req.headers) : req.headers
headers.host = url.hostname
const queryString = getQueryString(url.search, req.url, opts)
var body = ''
Expand Down Expand Up @@ -89,11 +90,19 @@ module.exports = fp(function from (fastify, opts, next) {
internal.end(body)
}

internal.on('error', this.send.bind(this))
internal.on('error', (err) => {
req.log.warn(err, 'response errored')
this.send(err)
})

internal.on('response', (res) => {
req.log.info('response received')

copyHeaders(rewriteHeaders(res), this)
if (isHttp2) {
copyHeadersHttp2(rewriteHeaders(res), this)
} else {
copyHeaders(rewriteHeaders(res), this)
}

this.code(res.statusCode)

Expand Down Expand Up @@ -128,6 +137,47 @@ function copyHeaders (headers, reply) {
}
}

// HTTP2 version specific for copyHeaders
// this handles headers with ':' in front
function copyHeadersHttp2 (headers, reply) {
const headersKeys = Object.keys(headers)

var i
var header

for (i = 0; i < headersKeys.length; i++) {
header = headersKeys[i]

// TODO what other http1-specific headers exists?
switch (header) {
case 'connection':
break
// case 'date':
// break
default:
reply.header(header, headers[header])
break
}
}
}

function http2toHttp1Headers (headers) {
const dest = {}
const headersKeys = Object.keys(headers)

var i
var header

for (i = 0; i < headersKeys.length; i++) {
header = headersKeys[i]
if (header.charCodeAt(0) !== 58) { // fast path for indexOf(':') === 0
dest[header] = headers[header]
}
}

return dest
}

function agentOption (opts) {
return {
keepAlive: true,
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
"homepage": "https://github.com/fastify/fastify-reply-from#readme",
"devDependencies": {
"fastify": "^0.43.0",
"got": "^8.2.0",
"h2url": "^0.1.2",
"msgpack5": "^4.0.1",
"nock": "^9.1.6",
"pre-commit": "^1.2.2",
Expand Down
78 changes: 78 additions & 0 deletions test/http2-https.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
'use strict'

const h2url = require('h2url')
const t = require('tap')
const Fastify = require('fastify')
const From = require('..')
const got = require('got')
const fs = require('fs')
const path = require('path')
const certs = {
allowHTTP1: true, // fallback support for HTTP1
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'fastify.key')),
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'fastify.cert'))
}

const instance = Fastify({
http2: true,
https: certs
})

t.plan(4)
t.tearDown(instance.close.bind(instance))

const target = Fastify({
https: certs
})

target.get('/', (request, reply) => {
t.pass('request proxied')
reply.code(404).header('x-my-header', 'hello!').send({
hello: 'world'
})
})

instance.get('/', (request, reply) => {
reply.from()
})

t.tearDown(target.close.bind(target))

async function run () {
await target.listen(0)

instance.register(From, {
base: `https://localhost:${target.server.address().port}`,
rejectUnauthorized: false
})

await instance.listen(0)

t.test('http2 -> https', async (t) => {
const { headers, body } = await h2url.concat({
url: `https://localhost:${instance.server.address().port}`
})

t.equal(headers[':status'], 404)
t.equal(headers['x-my-header'], 'hello!')
t.equal(headers['content-type'], 'application/json')
t.deepEqual(JSON.parse(body), { hello: 'world' })
})

t.test('https -> https', async (t) => {
try {
await got(`https://localhost:${instance.server.address().port}`, {
rejectUnauthorized: false
})
} catch (err) {
t.equal(err.response.statusCode, 404)
t.equal(err.response.headers['x-my-header'], 'hello!')
t.equal(err.response.headers['content-type'], 'application/json')
t.deepEqual(JSON.parse(err.response.body), { hello: 'world' })
return
}
t.fail()
})
}

run()