Skip to content
This repository has been archived by the owner on Sep 6, 2018. It is now read-only.

Commit

Permalink
reuse connection and close connection
Browse files Browse the repository at this point in the history
  • Loading branch information
devsnek committed Feb 23, 2018
1 parent 1032a5b commit 3b0b531
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
24 changes: 21 additions & 3 deletions src/node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,20 @@ function request(snek, options = snek.options) {
options.headers['content-length'] = length;
}

let req;
let http2 = false;
try {
var { req, http2 } = await socket(options);
if (options.connection) {
req = socket.http2req(options.connection, options);
http2 = true;
} else {
const O = await socket(options);
req = O.req;
if (O.http2)
http2 = true;
if (O.connection)
options.connection = O.connection;
}
} catch (err) {
reject(err);
return;
Expand All @@ -40,11 +52,13 @@ function request(snek, options = snek.options) {
req.on('error', reject);

const body = [];
let headers = {};
let statusCode = -1;
let headers;
let statusCode;
let statusText;

const handleResponse = (stream) => {
if (statusCode === undefined)
throw new Error('response timing error');
if (options.redirect === 'follow' && [301, 302, 303, 307, 308].includes(statusCode)) {
resolve(request(snek, {
...options,
Expand Down Expand Up @@ -73,6 +87,10 @@ function request(snek, options = snek.options) {
stream.once('end', () => {
snek.push(null);
const raw = Buffer.concat(body);
if (headers === undefined)
throw new Error('response timing error');
if (options.connection)
options.connection.close();
resolve({ raw, headers, statusCode, statusText });
});
};
Expand Down
18 changes: 12 additions & 6 deletions src/node/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,8 @@ function connectHttps(opt) {
createConnection: () => socket,
});

const req = connection.request(Object.assign({
':path': opt.path,
':method': opt.method,
':authority': opt.host,
}, opt.headers));
resolve({ req, http2: true });
const req = http2req(connection, opt);
resolve({ req, http2: true, connection });
break;
}
default:
Expand All @@ -60,5 +56,15 @@ function connectHttps(opt) {
});
}

function http2req(connection, opt) {
return connection.request(Object.assign({
':path': opt.path,
':method': opt.method,
':authority': opt.host,
}, opt.headers));
}

module.exports = (options) =>
(options.protocol === 'https:' ? connectHttps : connectHttp)(options);

module.exports.http2req = http2req;

0 comments on commit 3b0b531

Please sign in to comment.