Skip to content

Instantly share code, notes, and snippets.

@dumpsayamrat
Created May 31, 2018 16:37
Show Gist options
  • Save dumpsayamrat/8a66e34daa3b1617ccbcb23a1b9cbc84 to your computer and use it in GitHub Desktop.
Save dumpsayamrat/8a66e34daa3b1617ccbcb23a1b9cbc84 to your computer and use it in GitHub Desktop.
HTTP/2 (server.js)
'use strict'
const http2 = require('http2')
const fs = require('fs')
const path = require('path')
const helper = require('./helper')
const { HTTP2_HEADER_PATH } = http2.constants
const PUBLIC_PATH = path.join(__dirname, '../public')
const SSL_PATH = path.join(__dirname, '../ssl')
const publicFiles = helper.getFiles(PUBLIC_PATH)
function push(stream, path) {
const file = publicFiles.get(path)
if (!file) {
return
}
stream.pushStream({ [HTTP2_HEADER_PATH]: path }, { parent: stream.id }, (err, pushStream, headers) => {
if (err) throw err
pushStream.respondWithFD(file.fileDescriptor, file.headers)
})
}
const server = http2.createSecureServer({
key: fs.readFileSync(SSL_PATH + '/server.key'),
cert: fs.readFileSync(SSL_PATH + '/server.crt')
})
server.on('stream', (stream, headers) => {
console.log(headers[':path'])
const reqPath = headers[':path'] === '/' ? '/index.html' : headers[':path']
const file = publicFiles.get(reqPath)
if(!file) {
stream.statusCode = 404
stream.end()
return
}
if (reqPath === '/index.html') {
push(stream, '/styles.css')
push(stream, '/app.js')
}
stream.respondWithFD(file.fileDescriptor, file.headers)
})
server.on('error', (err) => console.error(err))
server.listen(3030)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment