Skip to content

Instantly share code, notes, and snippets.

@kanatohodets
Last active November 8, 2019 04:09
Show Gist options
  • Save kanatohodets/a0e421415a3506308d5e to your computer and use it in GitHub Desktop.
Save kanatohodets/a0e421415a3506308d5e to your computer and use it in GitHub Desktop.
Mojo::UserAgent over a unix socket
#!/usr/bin/env perl
use strict;
use warnings;
use 5.20.0;
use IO::Socket::UNIX;
use Mojo::Util qw(monkey_patch);
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
# these get called by Mojo::UA
monkey_patch 'IO::Socket::UNIX', (
sockhost => sub { '' },
peerhost => sub { '' },
sockport => sub { -1; },
peerport => sub { -1; }
);
# too evil?
monkey_patch 'Mojo::UserAgent', (non_unix_start => \&Mojo::UserAgent::start);
monkey_patch 'Mojo::UserAgent', (
start => sub {
my ($self, $tx, $cb) = @_;
if ($tx->req->url->scheme eq 'unix') {
my $path = $tx->req->url->path;
# pull out the sock_path ('host') and url path.
my $sock_path = ($path =~ m#(^.+\.sock)\/#)[0];
my $url_path = $path =~ s/$sock_path//r;
$tx->req->url->path($url_path);
if (-S $sock_path) {
my $sock = IO::Socket::UNIX->new(Peer => $sock_path);
$tx->connection($sock);
} else {
$tx->res->error({message => "$sock_path is not a socket."});
}
}
$self->non_unix_start($tx, $cb);
}
);
my $tx = $ua->get('unix:///var/run/docker.sock/images/json?all=true');
say $tx->res->body;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment