forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
/
h2c.js
51 lines (41 loc) · 1002 Bytes
/
h2c.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import http2 from 'http2-wrapper';
import got from '../../dist/source/index.js';
let sessions = {};
const getSession = ({origin}) => {
if (sessions[origin] && !sessions[origin].destroyed) {
return sessions[origin];
}
const session = http2.connect(origin);
session.once('error', () => {
delete sessions[origin];
});
sessions[origin] = session;
return session;
};
const closeSessions = () => {
for (const key in sessions) {
sessions[key].close();
}
sessions = {};
};
const instance = got.extend({
hooks: {
beforeRequest: [
options => {
options.h2session = getSession(options.url);
options.http2 = true;
options.request = http2.request;
}
]
}
});
const server = http2.createServer((request, response) => {
response.end('{}');
});
server.listen(async () => {
const url = `http://localhost:${server.address().port}`;
const {body, headers} = await instance(url, {context: {h2c: true}});
console.log(headers, body);
closeSessions();
server.close();
});