Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added option for custom headers #887

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ This will install `http-server` globally so that it may be run from the command
|`-e` or `--ext` |Default file extension if none supplied |`html` |
|`-s` or `--silent` |Suppress log messages from output | |
|`--cors` |Enable CORS via the `Access-Control-Allow-Origin` header | |
|`-H` or `--header` |Add an extra response header (can be used several times) | |
|`-o [path]` |Open browser window after starting the server. Optionally provide a URL path to open. e.g.: -o /other/dir/ | |
|`-c` |Set cache time (in seconds) for cache-control max-age header, e.g. `-c10` for 10 seconds. To disable caching, use `-c-1`.|`3600` |
|`-U` or `--utc` |Use UTC time format in log messages.| |
Expand Down
35 changes: 33 additions & 2 deletions bin/http-server
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ var chalk = require('chalk'),
url = require('url');
var argv = require('minimist')(process.argv.slice(2), {
alias: {
tls: 'ssl'
tls: 'ssl',
header: 'H'
}
});
var ifaces = os.networkInterfaces();
Expand All @@ -35,6 +36,9 @@ if (argv.h || argv.help) {
' -s --silent Suppress log messages from output',
' --cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header',
' Optionally provide CORS headers list separated by commas',
' -H',
' --header',
' Add an extra response header (can be used several times)',
' -o [path] Open browser window after starting the server.',
' Optionally provide a URL path to open the browser window to.',
' -c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.',
Expand Down Expand Up @@ -153,16 +157,35 @@ function listen(port) {
showDotfiles: argv.dotfiles,
mimetypes: argv.mimetypes,
username: argv.username || process.env.NODE_HTTP_SERVER_USERNAME,
password: argv.password || process.env.NODE_HTTP_SERVER_PASSWORD
password: argv.password || process.env.NODE_HTTP_SERVER_PASSWORD,
headers: {}
};

function setHeader(str) {
const m = /^(.+?)\s*(:\s*(.*))$/.exec(str);
if (!m || m.length < 4) {
options.headers[str] = '';
} else {
options.headers[m[1]] = m[3];
}
}

if (argv.cors) {
options.cors = true;
if (typeof argv.cors === 'string') {
options.corsHeaders = argv.cors;
}
}

if (argv.header) {
if (Array.isArray(argv.header)) {
argv.header.forEach(h => setHeader(h));
}
else {
setHeader(argv.header);
}
}

if (proxy) {
try {
new url.URL(proxy)
Expand Down Expand Up @@ -219,6 +242,14 @@ function listen(port) {
([chalk.yellow('Default File Extension: '), argv.e ? chalk.cyan(argv.e) : (argv.ext ? chalk.cyan(argv.ext) : chalk.red('none'))].join(''))
].join('\n'));

if (options.headers) {
logger.info(chalk.yellow('Additional Headers:'));
for (let k in options.headers) {
let v = options.headers[k];
logger.info(chalk.yellow(`\t${k}:`) + chalk.cyan(` ${v}`));
}
}

logger.info(chalk.yellow('\nAvailable on:'));

if (argv.a && host !== '0.0.0.0') {
Expand Down
4 changes: 4 additions & 0 deletions doc/http-server.1
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ Suppress log messages from output.
Enable CORS via the "Access-Control-Allow-Origin" header.
Optionally provide CORS headers list separated by commas.

.TP
.BI \-H ", " \-\-header " " \fIHEADER\fR
Add an extra response header (can be used several times)

.TP
.BI \-o " " [\fIPATH\fR]
Open default browser window after starting the server.
Expand Down
65 changes: 64 additions & 1 deletion test/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,67 @@ test('--proxy requires you to specify a protocol', (t) => {
server.on('exit', (code) => {
t.equal(code, 1);
});
});
});

function doHeaderOptionTest(t, argv, obj) {
const options = ['.', '--port', defaultPort].concat(argv);
const server = startServer(options);

tearDown(server, t);

server.stdout.on('data', (msg) => {
checkServerIsRunning(`http://localhost:${defaultPort}`, msg, t, (err, res) => {
t.error(err);

for (const [k, v] of Object.entries(obj)) {
t.equal(res.headers[k], v, 'expected header value matches in response');
}
});
});
}

test('single --header option is applied', (t) => {
t.plan(4);

doHeaderOptionTest(t,
['--header=X-http-server-test-A: hello'],
{ 'x-http-server-test-a': 'hello' }
);
});

test('single -H option is applied', (t) => {
t.plan(4);

doHeaderOptionTest(t,
['-H', 'X-http-server-test-A: hello'],
{ 'x-http-server-test-a': 'hello' }
);
});

test('mix of multiple --header and -H options are applied', (t) => {
t.plan(7);

doHeaderOptionTest(t,
[
'--header=X-http-server-test-A: Lorem ipsum dolor sit amet',
'-H', 'X-http-server-test-B: consectetur=adipiscing; elit',
'-H', 'X-http-server-test-C: c',
'--header=X-http-server-test-D: d'
],
{
'x-http-server-test-a': 'Lorem ipsum dolor sit amet',
'x-http-server-test-b': 'consectetur=adipiscing; elit',
'x-http-server-test-c': 'c',
'x-http-server-test-d': 'd'
}
);
});

test('empty header value is allowed (RFC 7230)', (t) => {
t.plan(5);

doHeaderOptionTest(t,
['-H', 'X-http-server-test-empty-a:', '-H', 'X-http-server-test-empty-b'],
{ 'x-http-server-test-empty-a': '', 'x-http-server-test-empty-b': '' }
);
});