ã¡ãã£ã¨æ¸ãã¦ã¿ãããªã£ãã®ã§æ¸ãããå®ç¨æ§ã¨ãæ°ã«ãã¡ããããªãã
$ node reverse_proxy.js d.hatena.ne.jp reverse proxy to d.hatena.ne.jp http://localhost:8000
ãã㧠localhost:8000 â d.hatena.ne.jp ã® reverse proxy ã«ãªãã¾ãã
ãã£ã¦ããã¨ã¯åç´ã§ã
- http server ãèµ·å
- client ããæ¥ã request ã® Host ãå·®ãæ¿ã㦠upstream ã«æãã
- upstream ããåãåã£ã response ã client ã«è¿ã
ã ãã§ããä¾ã«ãã£ã¦ã¤ãã³ãé§åãªã®ã§ãhttp body ãæ±ãã«ã¯ addListener ããå½¢ã§ããã
æ¬æ¥ã¯ body ã®ä¸èº« (HTMLå
ã® URL ã¨ã) ãæ¸ãæãããããªãã®ã欲ããã£ãã®ã§ãããutf8 以å¤ã®æåã³ã¼ããæ±ãã®ãé¢åãªã®ã§ããã¾ã§ã
# utf8 以å¤ã¯ chunk ãæååãããªãã¦ãbyte ã®å
¥ã£ã Object ã¨ãã¦æ±ãå¿
è¦ãããã¾ã
var sys = require('sys'), http = require('http'), port = 8000, upstreamHost = process.argv[2]; var main = function() { http.createServer(handle_request).listen(port); sys.puts("reverse proxy to " + upstreamHost + " http://localhost:" + port ); }; var handle_request = function (client_request, client_response) { var upstream = http.createClient(80, upstreamHost); var localhost = client_request.headers.host; client_request.headers.host = upstreamHost; var upstream_request = upstream.request( client_request.method, client_request.url, client_request.headers ); client_request.addListener("data", function(chunk) { upstream_request.write(chunk) }); client_request.addListener("end", function() { upstream_request.end(); }); upstream_request.addListener("response", function (upstream_response) { proxy_pass_reverse(upstream_response, localhost); client_response.writeHead( upstream_response.statusCode, upstream_response.headers ); var size = 0; upstream_response.addListener("data", function(chunk) { client_response.write(chunk); size += chunk.length; }); upstream_response.addListener("end", function() { sys.puts(client_request.method + " " + client_request.url + " " + upstream_response.statusCode + " " + size); client_response.end(); }); }); }; // Location ãããã®æ¸ãæã var proxy_pass_reverse = function(upstream_response, localhost) { var location = upstream_response.headers["location"]; if (location) { upstream_response.headers.location = location.replace( upstreamHost, localhost ); sys.puts("new location: " + upstream_response.headers.location); } }; main();