通过 littleproxy 创建反向代理

Create a reverse proxy by littleproxy

我是 littleproxy 的新手,如何创建反向代理服务器?

我的代理从客户端获取请求并将它们发送到服务器(服务器只是一个与 www.xxx.com 相同的常规站点,仅包含网页(不休息)并且代理从服务器(网页)获取响应和return 给客户。

例如,客户端url是localhost:8080/x,代理将其映射到www.myserver.com/xy并为客户端显示xy页面。如何使用过滤器或 httpservlet 来做到这一点。

我的 http servlet 将如下所示:

 public class ProxyFilter implements Filter {
      public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        HttpProxyServer server =
        DefaultHttpProxyServer.bootstrap()
        .withPort(8080)
        .withFiltersSource(new HttpFiltersSourceAdapter() {
            public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) {
               return new HttpFiltersAdapter(originalRequest) {
                  @Override
                  public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return null;
                  }

                  @Override
                  public HttpResponse proxyToServerRequest(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return null;
                  }

                  @Override
                  public HttpObject serverToProxyResponse(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return httpObject;
                  }

                  @Override
                  public HttpObject proxyToClientResponse(HttpObject httpObject) {
                      // TODO: implement your filtering here ????
                      return httpObject;
                  }   
               };
            }
        })
        .start();
    }
    public void init(FilterConfig config) throws ServletException {

    }
    public void destroy() {

    }
}

LittleProxy 使用 Host header 进行路由。您可以做的最简单的事情就是在 clientToProxyRequest 方法中将 Host 设置为真实服务器。


    public HttpResponse clientToProxyRequest(HttpObject httpObject) {
        if(httpObject instanceof FullHttpRequest) {
            FullHttpRequest httpRequest = (FullHttpRequest)httpObject;
            httpRequest.headers().remove("Host");
            httpRequest.headers().add("Host", "myserver.com:8080");
        }
        return null;
    }