Files: 6d09dd8687c742866f2799345a876eaf0d9f002d / proxy.js
1225 bytesRaw
1 | const http = require('http') |
2 | const httpProxy = require('http-proxy') |
3 | const Url = require('url') |
4 | const startsWith = require('lodash').startsWith |
5 | const assign = require('lodash').assign |
6 | |
7 | const config = require('app/config') |
8 | |
9 | const proxy = httpProxy.createProxyServer({ |
10 | ignorePath: true |
11 | }) |
12 | |
13 | const server = http.createServer(function (req, res) { |
14 | const url = Url.parse(req.url) |
15 | if (matches(config.api, url.pathname)) { |
16 | proxy.web(req, res, { target: targetUrl(config.api, url.pathname) }) |
17 | } else if (matches(config.static, url.pathname)) { |
18 | proxy.web(req, res, { target: targetUrl(config.static, url.pathname) }) |
19 | } else { |
20 | proxy.web(req, res, { target: targetUrl(config.render, url.pathname) }) |
21 | } |
22 | }) |
23 | |
24 | server.listen(config.proxy.port, function () { |
25 | console.log(`proxy server listening on port ${config.proxy.port}`) |
26 | }) |
27 | |
28 | function targetUrl (service, pathname) { |
29 | const url = assign( |
30 | {}, service.url, |
31 | { port: service.port }, |
32 | { pathname: targetPath(service, pathname) } |
33 | ) |
34 | return Url.format(url) |
35 | } |
36 | |
37 | function targetPath (service, pathname) { |
38 | return pathname.slice(service.url.pathname.length - 1) |
39 | } |
40 | |
41 | function matches (service, pathname) { |
42 | return startsWith(pathname, service.url.pathname) |
43 | } |
44 |
Built with git-ssb-web