Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active July 13, 2018 15:06
Show Gist options
  • Save daliborgogic/f5f068a6b44818c018a944ad4db73544 to your computer and use it in GitHub Desktop.
Save daliborgogic/f5f068a6b44818c018a944ad4db73544 to your computer and use it in GitHub Desktop.
HTTP2 server push example [Pre-compressed with brotli]
// Native
const http2 = require('http2')
const fs = require('fs')
const path = require('path')
// Packages
const cert = require('openssl-self-signed-certificate')
const mime = require('mime')
const {
HTTP2_HEADER_PATH,
HTTP_STATUS_NOT_FOUND,
HTTP_STATUS_INTERNAL_SERVER_ERROR
} = http2.constants
const options = {
key: cert.key,
cert: cert.cert,
passphrase: cert.passphrase
}
const PUBLIC = '/dist'
const COMPRESSED = path.join(__dirname, 'compressed')
const server = http2.createSecureServer(options)
function respondError (err, stream) {
(err.code === 'ENOENT')
? stream.respond({ ':status': HTTP_STATUS_NOT_FOUND })
: stream.respond({ ':status': HTTP_STATUS_INTERNAL_SERVER_ERROR })
stream.end()
}
server.on('stream', (stream, headers) => {
const reqPath = headers[HTTP2_HEADER_PATH]
const fullPath = path.join(__dirname, reqPath)
const respondType = mime.getType(fullPath)
if (reqPath === '/') {
stream.respondWithFile(`${COMPRESSED}/index.br`, {
'content-type': 'text/html',
'content-encoding': 'br'
}, {
onError: err => respondError(err, stream)
})
stream.pushStream({ ':path': `${PUBLIC}/build.js` }, pushStream => {
pushStream.respondWithFile(`${COMPRESSED}/build.br`, {
'content-type': 'application/javascript',
'content-encoding': 'br'
}, { onError: err =>
respondError(err, pushStream)
})
})
} else {
stream.respondWithFile(`${COMPRESSED}/${path.parse(fullPath).name}.br`, {
'content-type': respondType,
'content-encoding': 'br'
}, {
onError: err => respondError(err, stream)
})
}
})
const PORT = process.env.PORT || 3443
server.listen(PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment