Skip to content

Commit

Permalink
feat(http): support server listening on multi-hosts
Browse files Browse the repository at this point in the history
  • Loading branch information
greenhat616 committed Jul 18, 2023
1 parent 5dec11b commit 466ca83
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 13 deletions.
2 changes: 1 addition & 1 deletion config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: 'hitokoto' # 服务名称,例如:hitokoto
url: 'https://v1.hitokoto.cn' # 服务地址,例如:https://v1.hitokoto.cn
api_name: 'demo_prprpr' # 服务标识,取个好区分的标识吧,例如:cd-01-demo
server: # 配置 HTTP 服务的信息
host: 127.0.0.1 # 监听的地址
hosts: 0.0.0.0 # 监听的地址
port: 8000 # 监听的端口
compress_body: true # 是否使用 GZIP 压缩
redis: # 配置 Redis
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "hitokoto",
"version": "1.7.1",
"version": "1.7.2-dev",
"description": "Fast & Powerful Hitokoto API Framework.",
"main": "core.js",
"engines": {
"node": ">=14"
},
"scripts": {
"start": "node core",
"dev": "yarn nodemon core.js -D",
"dev": "yarn nodemon -e js,mjs,cjs,json,yml,yaml core.js -- -D",
"pnpify": "yarn dlx @yarnpkg/pnpify",
"lint": "eslint ./src/**/*.js ./adapter/**/*.js ./test/**/*.js core.js",
"watch": "yarn dlx supervisor --watch \".\" --extensions \"js,json\" --exec \"yarn\" -- \"start\"",
Expand Down
4 changes: 3 additions & 1 deletion src/http/primary.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ module.exports = exports = {}

const workersNumber = nconf.get('workers') || os.cpus().length
const listeningPort = nconf.get('server:port') || 8000
const workers = new Workers({ workersNumber, listeningPort })
const listeningHosts =
nconf.get('server:host') || nconf.get('server:hosts') || '0.0.0.0'
const workers = new Workers({ workersNumber, listeningPort, listeningHosts })
const { requestsCounter } = require('../utils/master/requestsCounterMerge')

exports.startWorkersPool = async () => {
Expand Down
19 changes: 16 additions & 3 deletions src/http/worker.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const http = require('node:http')
const Koa = require('koa')
const chalk = require('chalk')
const nconf = require('nconf')
Expand All @@ -22,7 +23,9 @@ async function registerRoutes(routes) {
process.exit(1)
}
}
async function StartWebServer(isDev, port) {
async function StartWebServer(isDev, port, hosts) {
const { logger } = require('../logger')
logger.verbose(hosts)
await require('../middleware').register(app, isDev) // Register middlewares
const Routes = require('../route')
await registerRoutes(new Routes().routes())
Expand All @@ -39,7 +42,17 @@ async function StartWebServer(isDev, port) {
})
})
}
app.listen(port)
if (!hosts) {
http.createServer(app.callback()).listen(port)
return
}
hosts = typeof hosts === 'string' ? [hosts] : hosts
for (const host of hosts) {
logger.verbose(
`[http.Worker.StartWebServer] start http server on ${host}:${port}`,
)
http.createServer(app.callback()).listen(port, host)
}
}

function notifyMasterWorkerStarted() {
Expand Down Expand Up @@ -81,7 +94,7 @@ process.on('message', ({ key, data }) => {
.then(async () => {
const { recoverAB } = require('../utils')
await recoverAB()
await StartWebServer(isDev, data.port)
await StartWebServer(isDev, data.port, data.hosts)
})
.finally(() => {
const { logger } = require('../logger')
Expand Down
2 changes: 1 addition & 1 deletion src/prestart.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ function loadConfig(configFile, next, isChild = false, isDev = false) {
url: 'https://v1.hitokoto.cn',
api_name: 'undefined',
server: {
host: '127.0.0.1',
hosts: '0.0.0.0',
port: 8000,
compress_body: true,
},
Expand Down
21 changes: 16 additions & 5 deletions src/utils/master/workers.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ function setupCluster(params) {

class Workers {
workersNumbers = 0 // workers numbers
listeningHosts = '0.0.0.0'
listeningPort = 8000 // workers listening port
configFile = ''
isDev = false // debug mode
Expand All @@ -36,8 +37,9 @@ class Workers {
* @param {WorkersSettings} params
* @returns {boolean|any}
*/
constructor({ workersNumber, listeningPort }) {
constructor({ workersNumber, listeningPort, listeningHosts }) {
this.workersNumbers = workersNumber
this.listeningHosts = listeningHosts
this.listeningPort = listeningPort
this.configFile = nconf.get('config_file')
this.isDev = !!nconf.get('dev')
Expand Down Expand Up @@ -77,10 +79,18 @@ class Workers {
'[core.http.primary.Workers] %d workers will be spawned.',
this.workersNumbers,
)
logger.info(
'[core.http.primary.Workers] web server will listen on port: ' +
chalk.yellow(this.listeningPort),
)
const hosts =
typeof this.listeningHosts === 'string'
? [this.listeningHosts]
: this.listeningHosts
for (const host of hosts) {
logger.info(
`[core.http.primary.Workers] web server will listen on ${chalk.yellow(
host + ':' + this.listeningPort,
)}`,
)
}

for (let i = 0; i < this.workersNumbers; i++) {
this.spawnWorker()
}
Expand Down Expand Up @@ -116,6 +126,7 @@ class Workers {
key: 'start_server',
data: {
port: this.listeningPort,
hosts: this.listeningHosts,
},
})
}
Expand Down

0 comments on commit 466ca83

Please sign in to comment.