UNPKG

3.49 kBJavaScriptView Raw
1const http = require('http');
2const logger = require('./logger');
3const url = require('url');
4const path = require('path');
5const fs = require('fs');
6
7const httpServer = {
8 handlers: {
9 '/api/values': function (req) {
10 return ['value1', 'value2']
11 }
12 },
13 socketIOHandlers: {
14 '/send': function (paras) {
15 logger.info("httpServer",['socket.io:', '/chat', ' ', JSON.stringify(paras)].join(''));
16 }
17 }
18};
19
20/**
21 * processes different routes.
22 * @param route request route
23 * @param callback process request
24 */
25httpServer.addHandler = function (route, callback) {
26 if (typeof callback === 'function') {
27 httpServer.handlers[route] = callback;
28 }
29}
30
31/**
32 * processes different signalr routes.
33 * @param method request route
34 * @param callback process request
35 */
36httpServer.addSocketIOHandler = function (method, callback) {
37 if (typeof callback === 'function') {
38 httpServer.socketIOHandlers[method] = callback;
39 }
40}
41
42/**
43 *
44 * Starts http server listened to a address.
45 * @param host
46 * @param port
47 */
48httpServer.start = function (host, port) {
49 var server = http.createServer(function (req, res) {
50
51 var pathName = url.parse(req.url).pathname;
52
53 if (pathName.indexOf('/api') == 0) {
54 res.setHeader("ContentType", "text/json;charset=utf8");
55
56 if (typeof httpServer.handlers[pathName] === 'function') {
57 logger.warning("httpServer",['get/json', ' ', req.url, ' ', 'success'].join(''));//log request success.
58 var json = httpServer.handlers[pathName](req);
59 res.write(JSON.stringify({
60 status: 0,
61 code: 100,
62 msg: '',
63 data: json
64 }));
65 res.end();
66 } else {
67 _returnErr(req, res);
68 }
69 } else {
70 res.setHeader("ContentType", "text/html;charset=utf8");
71
72 var templatePath = path.join(__dirname, "../../../src/pages", [pathName, '.html'].join(''));
73 fs.readFile(templatePath, function (err, data) {
74 if (err) {
75 _returnErr(req, res);
76 } else {
77 logger.warning("httpServer",['get', ' ', req.url, ' ', 'success'].join(''));//log request success.
78 res.write(data);
79 res.end();
80 }
81 });
82 }
83 });
84
85 const io = require('socket.io')(server);
86
87 io.on("connection", client => {
88 if (httpServer.socketIOHandlers) {
89 for (var key in httpServer.socketIOHandlers) {
90 if (key && typeof httpServer.socketIOHandlers[key] === 'function') {
91 client.on(key, httpServer.socketIOHandlers[key]);
92 }
93 }
94 }
95 });
96
97 server.listen(port, host, function () {
98 logger.warning("httpServer",["Server started,please visit http://",host,':',port].join(''));
99 logger.info("httpServer",'Socket.io server started,url:/connection');
100 })
101}
102
103function _returnErr(req, res) {
104 logger.err("httpServer",['get', ' ', req.url, ' ', 'failed'].join(''));//log request failed.
105 res.writeHead(404, { 'ContentType': 'text/html;charset=utf8' });
106 res.write("404 Not found");
107 res.end();
108}
109module.exports = httpServer;
\No newline at end of file