Commit | Line | Data |
7ad87df9 |
1 | package Test::Rest; |
2 | |
930013e6 |
3 | use Moose; |
4 | use namespace::autoclean; |
7ad87df9 |
5 | |
6 | use LWP::UserAgent; |
7 | use Params::Validate qw(:all); |
8 | |
9 | sub new { |
10 | my $self = shift; |
e601adda |
11 | my %p = validate( @_, { |
12 | content_type => { type => SCALAR }, |
13 | }, |
14 | ); |
d34c067a |
15 | my $ref = { |
16 | 'ua' => LWP::UserAgent->new, |
7ad87df9 |
17 | 'content_type' => $p{'content_type'}, |
18 | }; |
19 | bless $ref, $self; |
20 | } |
21 | |
d34c067a |
22 | { |
23 | my @non_data_methods = qw(GET DELETE OPTIONS); |
24 | foreach my $method (@non_data_methods) { |
25 | no strict 'refs'; |
26 | my $sub = lc($method); |
27 | *$sub = sub { |
28 | my $self = shift; |
bc06b9a3 |
29 | my %p = validate( |
30 | @_, |
31 | { |
32 | url => { type => SCALAR }, |
33 | headers => { type => HASHREF, default => {} }, |
34 | }, |
35 | ); |
d34c067a |
36 | my $req = HTTP::Request->new( "$method" => $p{'url'} ); |
bc06b9a3 |
37 | $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} }; |
d34c067a |
38 | $req->content_type( $self->{'content_type'} ); |
39 | return $req; |
40 | }; |
41 | } |
7ad87df9 |
42 | |
d34c067a |
43 | my @data_methods = qw(PUT POST); |
44 | foreach my $method (@data_methods) { |
45 | no strict 'refs'; |
46 | my $sub = lc($method); |
47 | *{$sub} = sub { |
48 | my $self = shift; |
49 | my %p = validate( |
50 | @_, |
51 | { |
52 | url => { type => SCALAR }, |
53 | data => 1, |
bc06b9a3 |
54 | headers => { type => HASHREF, default => {} }, |
d34c067a |
55 | }, |
56 | ); |
57 | my $req = HTTP::Request->new( "$method" => $p{'url'} ); |
bc06b9a3 |
58 | $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} }; |
d34c067a |
59 | $req->content_type( $self->{'content_type'} ); |
60 | $req->content_length( |
61 | do { use bytes; length( $p{'data'} ) } |
62 | ); |
63 | $req->content( $p{'data'} ); |
64 | return $req; |
65 | }; |
66 | } |
7ad87df9 |
67 | } |
68 | |
7ad87df9 |
69 | 1; |
70 | |