File: Rest.pm

package info (click to toggle)
libcatalyst-action-serialize-data-serializer-perl 1.08-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 248 kB
  • sloc: perl: 2,409; makefile: 2
file content (70 lines) | stat: -rw-r--r-- 1,904 bytes parent folder | download | duplicates (8)
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
package Test::Rest;

use Moose;
use namespace::autoclean;

use LWP::UserAgent;
use Params::Validate qw(:all);

sub new {
    my $self = shift;
    my %p    = validate( @_, { 
            content_type => { type => SCALAR }, 
        }, 
    );
    my $ref  = {
        'ua'           => LWP::UserAgent->new,
        'content_type' => $p{'content_type'},
    };
    bless $ref, $self;
}

{
    my @non_data_methods = qw(HEAD GET DELETE OPTIONS);
    foreach my $method (@non_data_methods) {
        no strict 'refs';
        my $sub = lc($method);
        *$sub = sub {
            my $self = shift;
            my %p = validate(
                @_,
                {
                    url     => { type => SCALAR },
                    headers => { type => HASHREF, default => {} },
                },
            );
            my $req  = HTTP::Request->new( "$method" => $p{'url'} );
            $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} };
            $req->content_type( $self->{'content_type'} );
            return $req;
        };
    }

    my @data_methods = qw(PUT POST);
    foreach my $method (@data_methods) {
        no strict 'refs';
        my $sub = lc($method);
        *{$sub} = sub {
            my $self = shift;
            my %p    = validate(
                @_,
                {
                    url  => { type => SCALAR },
                    data => 1,
                    headers => { type => HASHREF, default => {} },
                },
            );
            my $req = HTTP::Request->new( "$method" => $p{'url'} );
            $req->header( $_ => $p{headers}{$_} ) for keys %{ $p{headers} };
            $req->content_type( $self->{'content_type'} );
            $req->content_length(
                do { use bytes; length( $p{'data'} ) }
            );
            $req->content( $p{'data'} );
            return $req;
        };
    }
}

1;