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 | params.push(config.port ?
|
57 | config.port :
|
58 | 0
|
59 | );
|
60 |
|
61 | var host = config.host;
|
62 |
|
63 | if(host !== '127.0.0.1' && host !== 'localhost') {
|
64 | params.push(config.host);
|
65 | }
|
66 |
|
67 | if(typeof callback === 'function') {
|
68 | params.push(callback);
|
69 | }
|
70 |
|
71 | this.server.listen.apply(this.server, params);
|
72 | };
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | NodeHTTPServer.prototype.close = function(callback) {
|
79 | this.server.close(callback);
|
80 | };
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | NodeHTTPServer.prototype._create_server = function(listener) {
|
89 | var credentials = this._config.ssl;
|
90 |
|
91 | if(!_isPlainObject(credentials)) {
|
92 | return HTTP.createServer(listener);
|
93 | }
|
94 |
|
95 | if(credentials.pfx) {
|
96 | credentials = {
|
97 | pfx: FS.readFileSync(credentials.pfx),
|
98 | passphrase: credentials.passphrase
|
99 | };
|
100 | } else if(credentials.key && credentials.cert) {
|
101 | credentials = {
|
102 | key: FS.readFileSync(credentials.key),
|
103 | cert: FS.readFileSync(credentials.cert),
|
104 | passphrase: credentials.passphrase
|
105 | };
|
106 | } else {
|
107 | Log.error('extension:ifnode-http', 'Wrong https credentials');
|
108 | }
|
109 |
|
110 | return HTTPS.createServer(credentials, listener);
|
111 | };
|
112 |
|
113 | module.exports = NodeHTTPServer;
|