1 | 'use strict';
|
2 |
|
3 | var _isPlainObject = require('lodash/isPlainObject');
|
4 | var Util = require('util');
|
5 | var FS = require('fs');
|
6 | var HTTP = require('http');
|
7 | var HTTPS = require('https');
|
8 |
|
9 | var Log = require('./../core/Log');
|
10 | var IConnectionServer = require('./../core/IConnectionServer');
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | function NodeHTTPServer(listener, config) {
|
21 | this._constructor(listener, config);
|
22 | }
|
23 |
|
24 | Util.inherits(NodeHTTPServer, IConnectionServer);
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | NodeHTTPServer.prototype._constructor = function(listener, config) {
|
32 | this._config = config;
|
33 |
|
34 | Object.defineProperty(this, 'server', {
|
35 | enumerable: true,
|
36 | value: this._create_server(listener)
|
37 | });
|
38 | };
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | NodeHTTPServer.prototype.configure = function(configurator) {
|
45 | configurator(this.server);
|
46 | };
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | NodeHTTPServer.prototype.listen = function(callback) {
|
53 | var config = this._config.local;
|
54 | var params = [];
|
55 |
|
56 | if(config.port) {
|
57 | params.push(config.port);
|
58 | }
|
59 |
|
60 | var host = config.host;
|
61 |
|
62 | if(host !== '127.0.0.1' && host !== 'localhost') {
|
63 | params.push(config.host);
|
64 | }
|
65 |
|
66 | if(typeof callback === 'function') {
|
67 | params.push(callback);
|
68 | }
|
69 |
|
70 | this.server.listen.apply(this.server, params);
|
71 | };
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | NodeHTTPServer.prototype.close = function(callback) {
|
78 | this.server.close(callback);
|
79 | };
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | NodeHTTPServer.prototype._create_server = function(listener) {
|
88 | var credentials = this._config.ssl;
|
89 |
|
90 | if(!_isPlainObject(credentials)) {
|
91 | return HTTP.createServer(listener);
|
92 | }
|
93 |
|
94 | if(credentials.pfx) {
|
95 | credentials = {
|
96 | pfx: FS.readFileSync(credentials.pfx, 'utf8')
|
97 | };
|
98 | } else if(credentials.key && credentials.cert) {
|
99 | credentials = {
|
100 | key: FS.readFileSync(credentials.key, 'utf8'),
|
101 | cert: FS.readFileSync(credentials.cert, 'utf8')
|
102 | };
|
103 | } else {
|
104 | Log.error('extension:ifnode-http', 'Wrong https credentials');
|
105 | }
|
106 |
|
107 | return HTTPS.createServer(credentials, listener);
|
108 | };
|
109 |
|
110 | module.exports = NodeHTTPServer;
|