Node v8.xのHTTP/2を試す、その2

続き

HTTP/2のpushも試す

今度はこんな感じ。createSecureServerにenablePushオプションを付けないとダメっぽい。

const http2 = require('http2');
const fs = require('fs')

const server = http2.createSecureServer({
    key: fs.readFileSync('./server.key'),
    cert: fs.readFileSync('./server.crt'),
    enablePush : true
});

server.on('stream', (stream, headers) => {
    if (headers[":path"] !== '/') {
        stream.respond({
            'content-type': 'text/plain',
            ':status': 404
        });
        stream.end('Not Found')
        return;
    }

    stream.respond({
        'content-type': 'text/html',
        ':status': 200
    });

    stream.pushStream({':path': '/hoge.js'}, (pushStream) => {
        pushStream.respond({
            'content-type': 'application/javascript',
            ':status': 200,
        });
        pushStream.end('window.alert("push")');
    });

    stream.end('<h1>Hello World</h1><script src="./hoge.js"></script>');
});

server.listen(8888);

普通に /hoge.js にアクセスすると404になってしまうが、/ にアクセスするとpushで /hoge.js が送りつけられるようにした。

f:id:paulownia:20171026011837p:plain

本番投入はexpressなどのフレームワークがHTTP2に対応しないと難しそうだが、試すだけなら非常に簡単。