| 1 | package HTTP::Tinyish::Base; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | for my $sub_name ( qw/get head put post delete patch/ ) { | ||
| 6 | my $req_method = uc $sub_name; | ||
| 7 | eval <<"HERE"; | ||
| 8 | sub $sub_name { | ||
| 9 | my (\$self, \$url, \$args) = \@_; | ||
| 10 | \@_ == 2 || (\@_ == 3 && ref \$args eq 'HASH') | ||
| 11 | or Carp::croak(q/Usage: \$http->$sub_name(URL, [HASHREF])/ . "\n"); | ||
| 12 | return \$self->request('$req_method', \$url, \$args || {}); | ||
| 13 | } | ||
| 14 | |||
| 15 | HERE | ||
| 16 | } | ||
| 17 | |||
| 18 | sub parse_http_header { | ||
| 19 | my($self, $header, $res) = @_; | ||
| 20 | |||
| 21 | # it might have multiple headers in it because of redirects | ||
| 22 | $header =~ s/.*^(HTTP\/\d(?:\.\d)?)/$1/ms; | ||
| 23 | |||
| 24 | # grab the first chunk until the line break | ||
| 25 | if ($header =~ /^(.*?\x0d?\x0a\x0d?\x0a)/) { | ||
| 26 | $header = $1; | ||
| 27 | } | ||
| 28 | |||
| 29 | # parse into lines | ||
| 30 | my @header = split /\x0d?\x0a/,$header; | ||
| 31 | my $status_line = shift @header; | ||
| 32 | |||
| 33 | # join folded lines | ||
| 34 | my @out; | ||
| 35 | for (@header) { | ||
| 36 | if(/^[ \t]+/) { | ||
| 37 | return -1 unless @out; | ||
| 38 | $out[-1] .= $_; | ||
| 39 | } else { | ||
| 40 | push @out, $_; | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | my($proto, $status, $reason) = split / /, $status_line, 3; | ||
| 45 | return unless $proto and $proto =~ /^HTTP\/(\d+)(\.(\d+))?$/i; | ||
| 46 | |||
| 47 | $res->{status} = $status; | ||
| 48 | $res->{reason} = $reason; | ||
| 49 | $res->{success} = $status =~ /^(?:2|304)/; | ||
| 50 | $res->{protocol} = $proto; | ||
| 51 | |||
| 52 | # import headers | ||
| 53 | my $token = qr/[^][\x00-\x1f\x7f()<>@,;:\\"\/?={} \t]+/; | ||
| 54 | my $k; | ||
| 55 | for my $header (@out) { | ||
| 56 | if ( $header =~ s/^($token): ?// ) { | ||
| 57 | $k = lc $1; | ||
| 58 | } elsif ( $header =~ /^\s+/) { | ||
| 59 | # multiline header | ||
| 60 | } else { | ||
| 61 | return -1; | ||
| 62 | } | ||
| 63 | |||
| 64 | if (exists $res->{headers}{$k}) { | ||
| 65 | $res->{headers}{$k} = [$res->{headers}{$k}] | ||
| 66 | unless ref $res->{headers}{$k}; | ||
| 67 | push @{$res->{headers}{$k}}, $header; | ||
| 68 | } else { | ||
| 69 | $res->{headers}{$k} = $header; | ||
| 70 | } | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | sub internal_error { | ||
| 75 | my($self, $url, $message) = @_; | ||
| 76 | |||
| 77 | return { | ||
| 78 | content => $message, | ||
| 79 | headers => { "content-length" => length($message), "content-type" => "text/plain" }, | ||
| 80 | reason => "Internal Exception", | ||
| 81 | status => 599, | ||
| 82 | success => "", | ||
| 83 | url => $url, | ||
| 84 | }; | ||
| 85 | } | ||
| 86 | |||
| 87 | 1; |