summary refs log tree commit diff
path: root/bin/http-console
blob: 3871c366095b93543f045c6d9e4dc58760ce9b07 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use strict;
use warnings;
use 5.010;

use Term::ReadLine;
use Getopt::Long;
use JSON;

my $url         = shift;
my $format_mode = 'append';
my $format      = 'json';

GetOptions(
    'm=s' => \$format_mode,
    'f=s' => \$format,
);

package http::net::console;
use MooseX::Net::API;

package main;

my ($content, $result);

my $term   = Term::ReadLine->new("http::net::console");
my $prompt = $url . '> ';
while (defined(my $in = $term->readline($prompt))) {
    map { http::net::console->meta->remove_net_api_method($_) }
      http::net::console->meta->get_all_api_methods();
    if ($in =~ /^(GET|DELETE)\s(.*)$/) {
        my $http_console = http::net::console->new(
            api_base_url    => $url,
            api_format      => $format,
            api_format_mode => $format_mode
        );
        $http_console->meta->add_net_api_method(
            'anonymous',
            method => $1,
            path   => $2
        );
        ($content, $result) = $http_console->anonymous;
        say JSON->new->pretty->encode($content);
    }
    elsif ($in =~ /^(POST|PUT)\s(.*)(?:\s(.*))$/) {
        my $method       = $1;
        my $path         = $2;
        my $data         = $3;
        my $http_console = http::net::console->new(
            api_base_url    => $url,
            api_format      => $format,
            api_format_mode => $format_mode,
        );
        $http_console->meta->add_net_api_method(
            'anonymous',
            method => $method,
            path   => $path
        );
        $http_console->api_useragent->add_handler(
            request_prepare => sub {
                my $request = shift;
                $request->content($data);
            }
        );
        ($content, $result) = $http_console->anonymous;
        say pretty_output($content);
    }
    elsif ($in eq 'show headers') {
        if (defined $result) {
            map { say $_ . ": " . $result->header($_) }
              keys %{$result->headers};
            say "";
        }
        else {
            say "no headers to show";
        }

    }
    elsif ($in eq 'show content') {
        if (defined $content) {
            say pretty_output($content);
        }
        else {
            say "no content to show";
        }
    }
}

sub pretty_output {
    JSON->new->pretty->encode(shift);
}