3.3. name-service 示例
name-service 会公开以下端点:
-
/api/name端点从greeting-service接收调用。如果name-service当前可用,/api/name端点会发送World!响应,以完成问候语。但是,如果name-service当前不可用,/api/name端点会发送Name 服务 down错误,其 HTTP 状态代码为500。 -
/api/state端点控制/api/name端点的当前行为。它决定了服务是否发送响应或出错信息。
以下代码示例演示了如何开发 name-service :
'use strict';
const path = require('path');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const probe = require('kube-probe');
const app = express();
const server = http.createServer(app);
// Adds basic health-check endpoints
probe(app);
let isOn = true;
const { update, sendMessage } = require('./lib/web-socket')(server, _ => isOn);
// Send and receive json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// CORS support
app.use(cors());
// Name service API
app.get('/api/name', (request, response) => {
if (isOn) {
response.send('World!');
} else {
response.status(500).send('Name service down');
}
sendMessage(`${new Date()} ${isOn ? 'OK' : 'FAIL'}`);
});
// Current state of service
app.put('/api/state', (request, response) => {
isOn = request.body.state === 'ok';
response.send({ state: isOn });
update();
});
app.get('/api/info',
(request, response) => response.send({ state: isOn ? 'ok' : 'fail' }));
// Expose the license.html at http[s]://[host]:[port]/licenses/licenses.html
app.use('/licenses', express.static(path.join(__dirname, 'licenses')));
module.exports = server;
'use strict';
const path = require('path');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const probe = require('kube-probe');
const app = express();
const server = http.createServer(app);
// Adds basic health-check endpoints
probe(app);
let isOn = true;
const { update, sendMessage } = require('./lib/web-socket')(server, _ => isOn);
// Send and receive json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// CORS support
app.use(cors());
// Name service API
app.get('/api/name', (request, response) => {
if (isOn) {
response.send('World!');
} else {
response.status(500).send('Name service down');
}
sendMessage(`${new Date()} ${isOn ? 'OK' : 'FAIL'}`);
});
// Current state of service
app.put('/api/state', (request, response) => {
isOn = request.body.state === 'ok';
response.send({ state: isOn });
update();
});
app.get('/api/info',
(request, response) => response.send({ state: isOn ? 'ok' : 'fail' }));
// Expose the license.html at http[s]://[host]:[port]/licenses/licenses.html
app.use('/licenses', express.static(path.join(__dirname, 'licenses')));
module.exports = server;