From c3cc6a11598d59f9fa54a204a9322bd5a0f8398f Mon Sep 17 00:00:00 2001 From: Eran Hammer Date: Mon, 3 Feb 2020 13:32:33 -0800 Subject: [PATCH] Add server.options.info.remote. Closes #4034 --- API.md | 6 ++++++ lib/config.js | 4 ++++ lib/request.js | 5 +++++ test/request.js | 6 +++++- 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/API.md b/API.md index fa2f7c43a..9fbd65405 100755 --- a/API.md +++ b/API.md @@ -142,6 +142,12 @@ Default value: the operating system hostname and if not available, to `'localhos The public hostname or IP address. Used to set [`server.info.host`](#server.info) and [`server.info.uri`](#server.info) and as [`address`](#server.options.address) is none provided. +### `server.options.info.remote` + +Default value: `false`. + +If `true`, the `request.info.remoteAddress` and `request.info.remotePort` are populated when the request is received which can consume more resource (but is ok if the information is needed, especially for aborted requests). When `false`, the fields are only populated upon demand (but will be `undefined` if accessed after the request is aborted). + #### `server.options.listener` Default value: none. diff --git a/lib/config.js b/lib/config.js index c87ddf82c..dd121b00d 100755 --- a/lib/config.js +++ b/lib/config.js @@ -249,6 +249,10 @@ internals.server = Joi.object({ .allow(false) .default(), host: Joi.string().hostname().allow(null), + info: Joi.object({ + remote: Joi.boolean().default(false) + }) + .default({}), listener: Joi.any(), load: Joi.object({ sampleInterval: Joi.number().integer().min(0).default(0) diff --git a/lib/request.js b/lib/request.js index 7f17aca0c..3111d4c1f 100755 --- a/lib/request.js +++ b/lib/request.js @@ -628,6 +628,11 @@ internals.Info = class { this.cors = null; this.responded = 0; this.completed = 0; + + if (request._core.settings.info.remote) { + this.remoteAddress; + this.remotePort; + } } get remoteAddress() { diff --git a/test/request.js b/test/request.js index e91feea3f..1a1f03444 100755 --- a/test/request.js +++ b/test/request.js @@ -410,14 +410,16 @@ describe('Request', () => { return stream; }; - const server = Hapi.server(); + const server = Hapi.server({ info: { remote: true } }); server.route({ method: 'GET', path: '/', handler }); let disconnected = 0; + let info; const onRequest = (request, h) => { request.events.once('disconnect', () => { + info = request.info; ++disconnected; }); @@ -462,6 +464,8 @@ describe('Request', () => { }); await server.stop(); + expect(info.remotePort).to.exist(); + expect(info.remoteAddress).to.exist(); }); it('handles aborted requests (pre response)', async () => {