#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
use Hijk;
use URI;

my ($method, $output_file, $header, $body) = ("GET", "-", "");
my $timeout = 60;
my $dump_header;
GetOptions(
    "method|X=s" => \$method,
    "H=s",       => \$header,
    'd=s',       => \$body,
    "output|o=s" => \$output_file,
    "timeout=s" => \$timeout,
    "D|dump-header=s" => \$dump_header,
);
$method = uc($method);

my $uri_string = shift(@ARGV) or die "$0 <url>";

my $uri = URI->new($uri_string);

my $res = Hijk::request {
    method => $method,
    host => $uri->host,
    port => $uri->port || 80,
    timeout => $timeout*1000,
    path => $uri->path,
    query_string => $uri->query,
    $header ? ( head => [split /: /, $header, 2] ) : (),
    $body   ? ( body => $body                    ) : (),
    parse_chunked => 1,
};

if ($dump_header) {
    for (keys %{$res->{head}}) {
        print "$_: $res->{head}{$_}\n";
    }
    print "\n";
}

print $res->{body};
