diff options
| author | RblSb <msrblsb@gmail.com> | 2020-04-30 04:29:56 +0300 |
|---|---|---|
| committer | RblSb <msrblsb@gmail.com> | 2020-04-30 04:29:56 +0300 |
| commit | d73ddaaa1823b38e6d1d1e402a5cee1755c2367a (patch) | |
| tree | 416d44c9f0d256c4fdb6b45b07dcc14b68271390 /src/server/HttpServer.hx | |
| parent | d751f4fb76d9e68d56d06b5d35aa0850def063e7 (diff) | |
Implement simple proxy
Diffstat (limited to 'src/server/HttpServer.hx')
| -rw-r--r-- | src/server/HttpServer.hx | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/server/HttpServer.hx b/src/server/HttpServer.hx index ec6ddda..0fc46fd 100644 --- a/src/server/HttpServer.hx +++ b/src/server/HttpServer.hx @@ -4,6 +4,9 @@ import sys.FileSystem; import js.node.Buffer; import haxe.io.Path; import js.node.Fs; +import js.node.Https; +import js.node.Http; +import js.node.Url; import js.node.http.IncomingMessage; import js.node.http.ServerResponse; import js.node.Path as JsPath; @@ -60,6 +63,11 @@ class HttpServer { return; } + if (url.startsWith("/proxy")) { + if (!proxyUrl(req, res)) res.end('Cannot proxy ${req.url}'); + return; + } + if (hasCustomRes) { final path = customDir + url; if (Fs.existsSync(path)) { @@ -126,6 +134,29 @@ class HttpServer { return data; } + static function proxyUrl(req:IncomingMessage, res:ServerResponse):Bool { + final url = req.url.replace("/proxy?url=", ""); + final url = Url.parse(js.Node.global.decodeURI(url)); + if (url.host == req.headers["host"]) return false; + final options = { + host: url.host, + port: Std.parseInt(url.port), + path: url.path, + method: req.method, + // headers: req.headers + }; + final request = url.protocol == "https:" ? Https.request : Http.request; + final proxy = request(options, proxyRes -> { + res.writeHead(proxyRes.statusCode, proxyRes.headers); + proxyRes.pipe(res, {end: true}); + }); + proxy.on("error", err -> { + res.end('Proxy error for ${url.href}'); + }); + req.pipe(proxy, {end: true}); + return true; + } + static function isChildOf(parent:String, child:String):Bool { final rel = JsPath.relative(parent, child); return rel.length > 0 && !rel.startsWith('..') && !JsPath.isAbsolute(rel); |
