Skip to content

Instantly share code, notes, and snippets.

@s1037989
Last active November 18, 2022 02:40
Show Gist options
  • Select an option

  • Save s1037989/d1583a64ed90a55bfac2e93a4a767379 to your computer and use it in GitHub Desktop.

Select an option

Save s1037989/d1583a64ed90a55bfac2e93a4a767379 to your computer and use it in GitHub Desktop.
use Mojolicious::Lite -signatures;
app->ua->max_redirects(10);
# Just forward the response
any '/*whatever' => {whatever => ''} => sub ($c) {
my $proxy_to = Mojo::URL->new($c->req->headers->header('X-Proxy-To') || $ENV{PROXY_TO}) or return $c->reply->not_found;
#my $proxy_for = Mojo::URL->new($c->req->headers->header('X-Proxy-For') || $ENV{PROXY_FOR}) or return $c->reply->not_found;
my $req = $c->req;
my $method = $req->method;
my $url = $req->url->to_abs;
my $headers = $req->headers->clone->dehop;
my $whatever = $c->param('whatever');
$c->log->debug(qq{Forwarding "$method $proxy_to/$whatever"});
# Clone and modify request headers
my $tx = $c->ua->build_tx($method => $proxy_to => $headers->to_hash);
$tx->req->url->path("/$whatever");
$tx->req->headers->host($url->host_port);
$tx->req->headers->header('X-Forwarded-For' => $c->tx->remote_address);
$tx->req->headers->header('X-Forwarded-Host' => $url->host_port);
$tx->req->headers->header('X-Forwarded-Proto' => $url->scheme);
$tx->req->headers->header('X-Request-Base' => $url->base);
#$tx->req->headers->header('Upgrade' => '');
$tx->req->headers->header('Connection' => 'upgrade');
$tx->req->headers->header('X-Proxy-Request' => 'MojoProxy/1.0');
warn sprintf "%s\n%s\n%s\n%s\n%s\n%s\n", '='x80, 'REQUEST', '-'x80, $c->req->to_string=~s/\r\n\r\n$//rs, '-'x80, $tx->req->to_string=~s/\r\n\r\n$//rs;
# Start non-blocking request
$c->proxy->start_p($tx)->catch(sub ($err) {
$c->log->error("Proxy error: $err");
$c->render(text => 'Could not connect to backend web service!', status => 400);
});
# Custom response
$tx->res->content->once(body => sub ($content) {
$c->res->headers->header('X-Proxy-Response' => 'MojoProxy/1.0');
warn sprintf "%s\n%s\n%s\n%s\n", '='x80, 'RESPONSE', '-'x80, $c->res->to_string;
warn $content->get_body_chunk(0);
});
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment