微服务之使用NodeJS创建HTTP代理服务器(反向代理)

本文介绍了一个简单的Node.js HTTP代理实现,该代理可用于学习目的。通过修改开源BI产品saiku中的NodeJS代理代码,作者创建了一个简易HTTP代理,并分享了其package.json及server.js文件的内容。

最近在做微服务相关产品,其中需要有API网关相关产品,虽然早有研究过API网关产品TYK,但是感觉其太重,想起之前研究开源BI产品saiku的时候,记得其有NodeJS的代理代码,于是看了下,颇有启发,略微修改了一些,拿出来跟大家分享下,虽然简单,不可用于生产,但是对于学习还是不错的

package.json

{
  "name": "SmartHttpProxy",
  "description": "An simplest Http Proxy",
  "version": "0.0.1",
  "author": "liuyg@liuyingguang.cn",
  "license": {
    "type": "Apache License Version 2"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js 8088 127.0.0.1 80 / "
  },
  "dependencies": {
    "express": "~4.13.4"
  }
}

server.js


/*
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 *
 * To play with the chaos monkey, set the CHAOS_MONKEY environment variable
 * to anything (Preferably a nice name for your chaos monkey).
 *
 * To start the server, run `node server.js [port] [backend_host] [backend_port]`
 */

// newer versions of node.js use the lower-case argv
var argv = process.ARGV || process.argv;

var http = require('http');
var express = require('express');
var path = require('path');
var app = express();
var port = process.env.C9_PORT || parseInt(argv[2], 10) || 8088;

var backend_host = argv[3] || 'httpbin.org';

var backend_port = argv[4] || 80;

var backend_path_prefix = argv[5] || '/';

var auth = argv[6] || null;

var standard_prefix = "/test/";

// Proxy request
function get_from_proxy(request, response) {

    // if a path prefix is set, remove the existing one
    if (backend_path_prefix !== '') {
      if (request.url.indexOf(standard_prefix) === 0) {
        request.url = backend_path_prefix + request.url.substr(standard_prefix.length);
      }
    }

    if (auth) {
        request.headers['authorization']     = 'Basic ' + new Buffer(auth).toString('base64');
        request.headers['www-authorization'] = 'Basic ' + new Buffer(auth).toString('base64');
        delete request.headers['cookie'];
    }

    var options = {
        hostname : backend_host,
        port     : backend_port,
        path     : request.url,
        method   : request.method,
        headers  : request.headers
    };

    console.log(options.method, options.path);

    var proxy_request = http.request(options);
    request.addListener('data', function(chunk) {
        proxy_request.write(chunk, 'binary');
    });
    request.addListener('end', function() {
        proxy_request.end();
    });

    proxy_request.addListener('error', function (error) {
        console.log("ERROR:",error);
    });
    proxy_request.addListener('response', function (proxy_response) {
        proxy_response.addListener('data', function(chunk) {
            response.write(chunk, 'binary');
        });

        proxy_response.addListener('end', function() {
                response.end();
        });
        response.writeHead(proxy_response.statusCode, proxy_response.headers);
    });
}

// Handle incoming requests
app.all("/test/*", function(request, response) {
    request.headers.host = backend_host;
    get_from_proxy(request, response);
});
console.log("Connected to '", backend_host, ":", backend_port,"'");
console.log("Proxy listening on", port);

app.listen(port, '0.0.0.0');

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值