UNPKG

youzanyun-devtool-worker

Version:

50 lines (49 loc) 1.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const http_1 = tslib_1.__importDefault(require("http")); const net_1 = tslib_1.__importDefault(require("net")); class HttpServer { constructor({ httpPort, httpsPort }) { this.httpPort = httpPort; this.httpsPort = httpsPort; } start(requestListener) { let httpProxyServer = http_1.default.createServer(); let that = this; httpProxyServer.on('request', requestListener); httpProxyServer.on('connect', (req, socket, head) => { this.connectHandle(req, socket, head); }); httpProxyServer.on('error', (err) => { console.error(err); }); httpProxyServer.listen(this.httpPort, "0.0.0.0"); console.log(`proxy http: ${this.httpPort}`); } async connectHandle(req, socket, head) { let proxyHost = "127.0.0.1"; let proxyPort = 443; let [host, port] = req.url.split(":"); let targetPort = +port; if (targetPort == 443) { proxyPort = this.httpsPort; } else { proxyHost = host; proxyPort = targetPort; } let conn = net_1.default.connect(proxyPort, proxyHost, () => { socket.write('HTTP/' + req.httpVersion + ' 200 OK\r\n\r\n', 'UTF-8', function () { conn.pipe(socket); socket.pipe(conn); }); }); conn.on("error", e => { console.error("err when connect to + " + proxyHost + " : " + proxyPort); console.error(e); }); } } exports.default = HttpServer; ;