Michael Soulier
Michael Soulier

Reputation: 821

Mojolicious - acting as an http proxy

I'm trying to implement a simple http proxy for certain requests for a simple web service using JSON as the payload.

I see some information on this, but no complete examples in the documentation. I've tried some code from blog posts that I found in google search results, but nothing that I could get working. Here is where I am.

The request is passed to a handler object, with a handle method like so

sub handle
{
    my $self = shift;
    my $app = shift;

    my $tx = $app->tx;
    my $req = $app->req->clone;
    $log->info("upstream host is " . $self->{upstream_host});
    $log->info("upstream port is " . $self->{upstream_port});
    $req->url->scheme("http")
            ->host($self->{upstream_host})
            ->port($self->{upstream_port});

    $log->info("req: " . $req->to_string);
    $log->info("req host:port " . $req->url->host . ":" . $req->url->port);

    my $ua = Mojo::UserAgent->new;
    my $tx = Mojo::Transaction::HTTP->new(req => $req);

    $log->info("response: " . $tx->res->to_string());

    $app->render(data => $tx->res->body);
}

Everything in the logs looks correct, but the response object is a 404 error, and no actual traffic reaches my other service listening on localhost:3334.

2013-07-02 12:28:26.929793500 [Tue Jul 2 12:28:26 2013] [info] req host:port 127.0.0.1:3334 2013-07-02 12:28:26.930225500 [Tue Jul 2 12:28:26 2013] [info] response: HTTP/1.1 404 Not Found

I tried the non-blocking version of this but again, no request was actually sent, so I tried to simplify.

Help appreciated, I'm not sure where I've gone wrong here. I'm just trying to duplicate the request, pass it to another service, and then return its response to the original client.

Thanks, Mike

Upvotes: 2

Views: 1165

Answers (1)

Michael Soulier
Michael Soulier

Reputation: 821

Ok, strange. This works.

sub handle
{
    my $self = shift;
    my $app = shift;

    my $tx = $app->tx;
    my $req = $app->req->clone;
    $log->debug("upstream host is " . $self->{upstream_host});
    $log->debug("upstream port is " . $self->{upstream_port});
    $req->url->scheme("http")
            ->host($self->{upstream_host})
            ->port($self->{upstream_port});

    $log->debug("req: " . $req->to_string);
    $log->debug("req host:port " . $req->url->host . ":" . $req->url->port);

    my $ua = Mojo::UserAgent->new;
    my $tx = $ua->start(Mojo::Transaction::HTTP->new(req => $req));

    $app->render(data => $tx->res->body);
}

I'm trying to see how that's significantly different from what I was already doing...

Now, this is a blocking request. Lets see if I can get it working non-blocking.

Upvotes: 2

Related Questions