Skip to content

Commit 8496916

Browse files
authored
feat: add random free port (midwayjs#4371)
* feat: support random port * fix: lint * fix: cycle dep
1 parent 8b5f766 commit 8496916

File tree

7 files changed

+110
-8
lines changed

7 files changed

+110
-8
lines changed

packages/web-express/src/framework.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import {
2929
MidwayExpressMiddlewareService,
3030
} from './middlewareService';
3131
import { debuglog } from 'util';
32-
import { sendData } from './util';
32+
import { getFreePort, sendData } from './util';
3333
const debug = debuglog('midway:debug');
3434

3535
@Framework()
@@ -189,8 +189,13 @@ export class MidwayExpressFramework extends BaseFramework<
189189
// register httpServer to applicationContext
190190
this.applicationContext.registerObject(HTTP_SERVER_KEY, this.server);
191191

192-
const customPort =
192+
let customPort =
193193
process.env.MIDWAY_HTTP_PORT ?? this.configurationOptions.port;
194+
195+
if (customPort === 0) {
196+
customPort = await getFreePort();
197+
}
198+
194199
if (customPort) {
195200
new Promise<void>(resolve => {
196201
const args: any[] = [customPort];
@@ -391,7 +396,7 @@ export class MidwayExpressFramework extends BaseFramework<
391396
return this.server;
392397
}
393398

394-
public getPort() {
399+
public getPort(): string {
395400
return process.env.MIDWAY_HTTP_PORT;
396401
}
397402

packages/web-express/src/util.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,24 @@
1+
import { AddressInfo, createServer } from 'net';
2+
13
export function sendData(res, data) {
24
if (typeof data === 'number') {
35
res.status(res.statusCode).send('' + data);
46
} else {
57
res.status(res.statusCode).send(data);
68
}
79
}
10+
11+
export async function getFreePort() {
12+
return new Promise<number>((resolve, reject) => {
13+
const server = createServer();
14+
server.listen(0, () => {
15+
try {
16+
const port = (server.address() as AddressInfo).port;
17+
server.close();
18+
resolve(port);
19+
} catch (err) {
20+
reject(err);
21+
}
22+
});
23+
});
24+
}

packages/web-express/test/index.test.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { closeApp, creatApp, createHttpRequest } from './utils';
2-
import { IMidwayExpressApplication, MidwayExpressMiddlewareService } from '../src';
2+
import { IMidwayExpressApplication, MidwayExpressMiddlewareService, Framework } from '../src';
33
import { createLightApp } from '@midwayjs/mock';
44

55
describe('/test/feature.test.ts', () => {
@@ -336,4 +336,21 @@ describe('/test/feature.test.ts', () => {
336336
expect(result.status).toEqual(403);
337337
await closeApp(app);
338338
});
339+
340+
it('should test get free port', async () => {
341+
const app = await createLightApp('', {
342+
imports: require('../src'),
343+
globalConfig: {
344+
keys: '12345',
345+
express: {
346+
port: 0,
347+
}
348+
}
349+
});
350+
351+
const port = (app.getFramework() as Framework).getPort();
352+
expect(port).not.toBe('0');
353+
console.log(process.env.MIDWAY_HTTP_PORT);
354+
await closeApp(app);
355+
});
339356
});

packages/web-koa/src/framework.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { Server } from 'http';
2929
import { setupOnError } from './onerror';
3030
import * as qs from 'qs';
3131
import * as querystring from 'querystring';
32+
import { getFreePort } from './utils';
3233

3334
const COOKIES = Symbol('context#cookies');
3435

@@ -312,8 +313,13 @@ export class MidwayKoaFramework extends BaseFramework<
312313
}
313314

314315
// set port and listen server
315-
const customPort =
316+
let customPort =
316317
process.env.MIDWAY_HTTP_PORT ?? this.configurationOptions.port;
318+
319+
if (customPort === 0) {
320+
customPort = await getFreePort();
321+
}
322+
317323
if (customPort) {
318324
new Promise<void>(resolve => {
319325
const args: any[] = [customPort];
@@ -349,7 +355,7 @@ export class MidwayKoaFramework extends BaseFramework<
349355
return this.server;
350356
}
351357

352-
public getPort() {
358+
public getPort(): string {
353359
return process.env.MIDWAY_HTTP_PORT;
354360
}
355361

packages/web-koa/src/utils.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { AddressInfo, createServer } from 'net';
2+
13
export function detectStatus(err) {
24
// detect status
35
let status = err.status || 500;
@@ -160,3 +162,18 @@ export function escapeHtml(string) {
160162

161163
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
162164
}
165+
166+
export async function getFreePort() {
167+
return new Promise<number>((resolve, reject) => {
168+
const server = createServer();
169+
server.listen(0, () => {
170+
try {
171+
const port = (server.address() as AddressInfo).port;
172+
server.close();
173+
resolve(port);
174+
} catch (err) {
175+
reject(err);
176+
}
177+
});
178+
});
179+
}

packages/web-koa/test/index.test.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { closeApp, creatApp, createHttpRequest } from './utils';
2-
import { IMidwayKoaApplication } from '../src';
2+
import { IMidwayKoaApplication, Framework } from '../src';
33
import { Controller, Get, makeHttpRequest } from '@midwayjs/core';
44
import { createLightApp } from '@midwayjs/mock';
55

@@ -481,6 +481,25 @@ describe('/test/feature.test.ts', () => {
481481
await closeApp(app);
482482
});
483483

484+
it('should test get random port', async () => {
485+
const app = await createLightApp('', {
486+
imports: [
487+
require('../src'),
488+
],
489+
globalConfig: {
490+
keys: '123',
491+
koa: {
492+
port: 0,
493+
}
494+
}
495+
});
496+
497+
const port = (app.getFramework() as Framework).getPort();
498+
expect(port).not.toBe('0');
499+
500+
await closeApp(app);
501+
});
502+
484503
describe('test query parser', () => {
485504
@Controller()
486505
class HomeController {

packages/web/src/framework/web.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { loggers, MidwayContextLogger } from '@midwayjs/logger';
2323
import { resolve } from 'path';
2424
import { Server } from 'net';
2525
import { debuglog } from 'util';
26+
import { AddressInfo, createServer } from 'net';
2627

2728
const debug = debuglog('midway:debug');
2829

@@ -274,7 +275,12 @@ export class MidwayWebFramework extends BaseFramework<
274275

275276
const eggConfig = this.configService.getConfiguration('egg');
276277
if (!this.isClusterMode && eggConfig) {
277-
const customPort = process.env.MIDWAY_HTTP_PORT ?? eggConfig.port;
278+
let customPort = process.env.MIDWAY_HTTP_PORT ?? eggConfig.port;
279+
280+
if (customPort === 0) {
281+
customPort = await getFreePort();
282+
}
283+
278284
if (customPort) {
279285
new Promise<void>(resolve => {
280286
const args: any[] = [customPort];
@@ -333,3 +339,18 @@ export class MidwayWebFramework extends BaseFramework<
333339
this.server = server;
334340
}
335341
}
342+
343+
async function getFreePort() {
344+
return new Promise<number>((resolve, reject) => {
345+
const server = createServer();
346+
server.listen(0, () => {
347+
try {
348+
const port = (server.address() as AddressInfo).port;
349+
server.close();
350+
resolve(port);
351+
} catch (err) {
352+
reject(err);
353+
}
354+
});
355+
});
356+
}

0 commit comments

Comments
 (0)