develooper Front page | perl.libwww | Postings from March 2003

Re: getting the last N bytes of something over HTTP

Thread Previous
From:
Gisle Aas
Date:
March 13, 2003 07:49
Subject:
Re: getting the last N bytes of something over HTTP
Message ID:
lr4r676zh3.fsf@caliper.activestate.com
"Sean M. Burke" <sburke@cpan.org> writes:

>   sub last_n_bytes {
>     my($browser, $url, $length_to_get) = @_;
> 
>     my $r = $browser->head( $url );
>     die "Can't HEAD-get $url\n" . $r->headers_as_string
>      . "\n Aborting" unless $r->is_success and $r->code == 200;
>     my $available_length;
>     die "Too short?\n" . $r->headers_as_string
>      . "\n\n Aborting" unless(
>      ($available_length = $r->content_length) > $length_to_get );
> 
>     my($start, $end) = (
>       $available_length - $length_to_get,
>       $available_length -              1,
>     );
>     
>     $r = $browser->get( $url,
>      'Range' => sprintf( "bytes=%s-%s", $start, $end),
>     );
> 
>     die "Can't get $url ($start-$end)\n" . $r->headers_as_string .
>      "\n\n Aborting"  unless $r->is_success;
> 
>     die "Wrong length!?" . $r->headers_as_string . "\n\n Aborting"
>      if $r->content_length > $length_to_get;
> 
>     return $r->content;
>   }

It is possible to express this directly in the Range header as well,
so I would just make it:

  sub last_n_bytes {
    my($browser, $url, $length_to_get) = @_;

    my $r = $browser->get( $url, Range => "bytes=-$length_to_get");
    die "Can't get $url ($length_to_get)\n" . $r->headers_as_string .
     "\n\n Aborting"  unless $r->is_success;

    return $r->content;
  }

Regards,
Gisle

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About