Convert the webserver to a proper class with private methods
This commit is contained in:
parent
440208daa6
commit
12b9685714
@ -38,7 +38,8 @@ var mimeTypes = {
|
|||||||
|
|
||||||
var defaultMimeType = "application/octet-stream";
|
var defaultMimeType = "application/octet-stream";
|
||||||
|
|
||||||
function WebServer() {
|
class WebServer {
|
||||||
|
constructor() {
|
||||||
this.root = ".";
|
this.root = ".";
|
||||||
this.host = "localhost";
|
this.host = "localhost";
|
||||||
this.port = 0;
|
this.port = 0;
|
||||||
@ -50,21 +51,23 @@ function WebServer() {
|
|||||||
GET: [crossOriginHandler],
|
GET: [crossOriginHandler],
|
||||||
POST: [],
|
POST: [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
WebServer.prototype = {
|
|
||||||
start(callback) {
|
start(callback) {
|
||||||
this._ensureNonZeroPort();
|
this.#ensureNonZeroPort();
|
||||||
this.server = http.createServer(this._handler.bind(this));
|
this.server = http.createServer(this.#handler.bind(this));
|
||||||
this.server.listen(this.port, this.host, callback);
|
this.server.listen(this.port, this.host, callback);
|
||||||
console.log(
|
console.log(
|
||||||
"Server running at http://" + this.host + ":" + this.port + "/"
|
"Server running at http://" + this.host + ":" + this.port + "/"
|
||||||
);
|
);
|
||||||
},
|
}
|
||||||
|
|
||||||
stop(callback) {
|
stop(callback) {
|
||||||
this.server.close(callback);
|
this.server.close(callback);
|
||||||
this.server = null;
|
this.server = null;
|
||||||
},
|
}
|
||||||
_ensureNonZeroPort() {
|
|
||||||
|
#ensureNonZeroPort() {
|
||||||
if (!this.port) {
|
if (!this.port) {
|
||||||
// If port is 0, a random port will be chosen instead. Do not set a host
|
// If port is 0, a random port will be chosen instead. Do not set a host
|
||||||
// name to make sure that the port is synchronously set by .listen().
|
// name to make sure that the port is synchronously set by .listen().
|
||||||
@ -76,8 +79,9 @@ WebServer.prototype = {
|
|||||||
this.port = address ? address.port : 8000;
|
this.port = address ? address.port : 8000;
|
||||||
server.close();
|
server.close();
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
_handler(req, res) {
|
|
||||||
|
#handler(req, res) {
|
||||||
var url = req.url.replaceAll("//", "/");
|
var url = req.url.replaceAll("//", "/");
|
||||||
var urlParts = /([^?]*)((?:\?(.*))?)/.exec(url);
|
var urlParts = /([^?]*)((?:\?(.*))?)/.exec(url);
|
||||||
try {
|
try {
|
||||||
@ -334,8 +338,8 @@ WebServer.prototype = {
|
|||||||
|
|
||||||
stream.pipe(res);
|
stream.pipe(res);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
// This supports the "Cross-origin" test in test/unit/api_spec.js
|
// This supports the "Cross-origin" test in test/unit/api_spec.js
|
||||||
// It is here instead of test.js so that when the test will still complete as
|
// It is here instead of test.js so that when the test will still complete as
|
||||||
|
Loading…
Reference in New Issue
Block a user