HTTP2
HTTP2
Fastify は HTTPS (h2) またはプレーンテキスト (h2c) で HTTP2 をサポートします。
現在、HTTP2 固有の API はいずれも Fastify 経由では使用できませんが、ノードの req
と res
には Request
と Reply
インターフェイスを通じてアクセスできます。PR は歓迎です。
セキュア (HTTPS)
HTTP2 はすべてのモダンブラウザでのみ セキュア接続経由で サポートされます
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')({
http2: true,
https: {
key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
}
})
fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
ALPN ネゴシエーションにより、同じソケットで HTTPS と HTTP/2 の両方をサポートできます。ノードコア req
と res
オブジェクトは HTTP/1 または HTTP/2 のいずれかになります。Fastify はすぐにこれをサポートします
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const fastify = require('fastify')({
http2: true,
https: {
allowHTTP1: true, // fallback support for HTTP1
key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
}
})
// this route can be accessed through both protocols
fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
新しいサーバーを次でテストできます。
$ npx h2url https://#:3000
プレーンテキストまたは非セキュア
マイクロサービスを構築している場合、プレーンテキストで HTTP2 に接続できますが、これはブラウザではサポートされていません。
'use strict'
const fastify = require('fastify')({
http2: true
})
fastify.get('/', function (request, reply) {
reply.code(200).send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
新しいサーバーを次でテストできます。
$ npx h2url https://#:3000