From f3ce1c300a79fab2f87c38cd853477e7756edb55 Mon Sep 17 00:00:00 2001 From: chenchao Date: Wed, 6 Nov 2019 18:13:23 +0800 Subject: [PATCH] more localhost use cases --- src/shared/urls.ts | 14 ++++++++++++-- test/shared/urls.test.ts | 14 +++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/shared/urls.ts b/src/shared/urls.ts index b256b20..ab01c49 100644 --- a/src/shared/urls.ts +++ b/src/shared/urls.ts @@ -5,7 +5,16 @@ const trimStart = (str: string): string => { return str.replace(/^\s+/, ''); }; -const SUPPORTED_PROTOCOLS = ['http:', 'https:', 'ftp:', 'mailto:', 'about:', 'localhost:']; +const SUPPORTED_PROTOCOLS = ['http:', 'https:', 'ftp:', 'mailto:', 'about:']; + +const isLocalhost = (url: string): boolean => { + if (url === 'localhost') { + return true; + } + + let [host, port] = url.split(':', 2); + return host === 'localhost' && !isNaN(Number(port)); +}; const searchUrl = (keywords: string, search: Search): string => { try { @@ -16,7 +25,8 @@ const searchUrl = (keywords: string, search: Search): string => { } catch (e) { // fallthrough } - if (keywords.includes('.') && !keywords.includes(' ')) { + if (isLocalhost(keywords) || + (keywords.includes('.') && !keywords.includes(' '))) { return 'http://' + keywords; } let template = search.engines[search.defaultEngine]; diff --git a/test/shared/urls.test.ts b/test/shared/urls.test.ts index 3a3eea6..d6f0550 100644 --- a/test/shared/urls.test.ts +++ b/test/shared/urls.test.ts @@ -36,6 +36,19 @@ describe("shared/commands/parsers", () => { expect(parsers.searchUrl('std::vector', config)) .to.equal('https://google.com/search?q=std%3A%3Avector'); }); + + it('localhost urls', () => { + expect(parsers.searchUrl('localhost', config)) + .to.equal('http://localhost'); + expect(parsers.searchUrl('http://localhost', config)) + .to.equal('http://localhost'); + expect(parsers.searchUrl('localhost:8080', config)) + .to.equal('http://locahost:8080'); + expect(parsers.searchUrl('localhost:80nan', config)) + .to.equal('https://google.com/search?q=localhost:80nan'); + expect(parsers.searchUrl('localhost 8080', config)) + .to.equal('https://google.com/search?q=localhost%208080'); + }) }); describe('#normalizeUrl', () => { @@ -47,4 +60,3 @@ describe("shared/commands/parsers", () => { }); }); }); -