HTTP-Cache-Transparent-1.4/000755 000765 000024 00000000000 13071765073 016253 5ustar00mattiasstaff000000 000000 HTTP-Cache-Transparent-1.4/Changes000644 000765 000024 00000004563 13071764761 017561 0ustar00mattiasstaff000000 000000 2017-04-07 Mattias Holmlund Version 1.4 Fix tests when run without internet connectivity. Patch by Mike Parker. Fixes https://rt.cpan.org/Ticket/Display.html?id=120584 2017-03-11 Mattias Holmlund Version 1.3 Added missing Changes entry for version 1.2. No other changes. 2017-03-07 Mattias Holmlund Version 1.2 Add X-No-Server-Contact header when the content returned has been delivered without any contact with the external server 2012-10-25 Mattias Holmlund Version 1.1 Unlink temporary cachefiles if we fail to give them a proper name Resolves https://rt.cpan.org/Ticket/Display.html?id=60065 Handle multiple simultaneous cache cleanups Hopefully resolves https://rt.cpan.org/Public/Bug/Display.html?id=77015 Handle caching of zero-size documents Resolves https://rt.cpan.org/Public/Bug/Display.html?id=76785 Populate $response->message with the default message for the code Patch from Graham Barr Ensure response has access to request when fetching from cache Patch from Graham Barr. Handle undefined content from servers. 2007-12-12 Mattias Holmlund Version 1.0 Add ApproveContent option. Add pod-tests. Mark internal methods with leading underscore. 2006-03-12 Mattias Holmlund Version 0.7 Add NoUpdate option. Remove Verbose output for HEAD requests. 2005-05-30 Mattias Holmlund Version 0.6 Handle invalid cache-directories. Create the cache directory if it doesn't exist. Store the headers Content-Type, Content-Length, Content-Encoding, Content-Range and Last-Modified in the cache and restore them when returning a cached response. Fix bug in ETag cache handling. 2004-12-08 Mattias Holmlund Version 0.5 Handle spaces in the path to the cache-dir. Handle multiple calls to init() without failing. 2004-10-24 Mattias Holmlund Version 0.4 Renamed from HTTP::TransparentCache to HTTP::Cache::Transparent on request from Brian D Foy on the modules@perl.org list. Add support for ranges. Added test-program from Nigel Horne. 2004-10-15 Mattias Holmlund Version 0.3 Support for libwww < 5.800 Only cache entries with response-code OK. Never delete files in cache with an invalid filename. Document cache format. 2004-10-11 Mattias Holmlund Release 0.2 Support initialization via use directive. Lower perl requirements to Perl 5.6.1. HTTP-Cache-Transparent-1.4/examples/000755 000765 000024 00000000000 13071765072 020070 5ustar00mattiasstaff000000 000000 HTTP-Cache-Transparent-1.4/lib/000755 000765 000024 00000000000 13071765072 017020 5ustar00mattiasstaff000000 000000 HTTP-Cache-Transparent-1.4/Makefile.PL000644 000765 000024 00000001152 13057617114 020220 0ustar00mattiasstaff000000 000000 use 5.006001; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'HTTP::Cache::Transparent', VERSION_FROM => 'lib/HTTP/Cache/Transparent.pm', # finds $VERSION PREREQ_PM => { LWP => 0, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'lib/HTTP/Cache/Transparent.pm', # retrieve abstract from module AUTHOR => 'Mattias Holmlund ') : ()), ); HTTP-Cache-Transparent-1.4/MANIFEST000644 000765 000024 00000000556 13071765073 017412 0ustar00mattiasstaff000000 000000 Changes Makefile.PL MANIFEST README.md t/HTTP-Cache-Transparent.t t/cache.t t/pod.t t/pod-coverage.t lib/HTTP/Cache/Transparent.pm examples/check_server examples/check_server_approve examples/test-range META.yml Module meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) HTTP-Cache-Transparent-1.4/META.json000644 000765 000024 00000001614 13071765073 017676 0ustar00mattiasstaff000000 000000 { "abstract" : "Cache the result of http get-requests persistently.", "author" : [ "Mattias Holmlund " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 6.66, CPAN::Meta::Converter version 2.133380", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "HTTP-Cache-Transparent", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "LWP" : "0" } } }, "release_status" : "stable", "version" : "1.4" } HTTP-Cache-Transparent-1.4/META.yml000644 000765 000024 00000001012 13071765072 017515 0ustar00mattiasstaff000000 000000 --- abstract: 'Cache the result of http get-requests persistently.' author: - 'Mattias Holmlund ' build_requires: ExtUtils::MakeMaker: 0 configure_requires: ExtUtils::MakeMaker: 0 dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 6.66, CPAN::Meta::Converter version 2.133380' license: unknown meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: HTTP-Cache-Transparent no_index: directory: - t - inc requires: LWP: 0 version: 1.4 HTTP-Cache-Transparent-1.4/README.md000644 000765 000024 00000002720 13057617203 017526 0ustar00mattiasstaff000000 000000 # HTTP-Cache-Transparent HTTP::Cache::Transparent is an implementation of http get that keeps a local cache of fetched pages to avoid fetching the same data from the server if it hasn't been updated. The cache is stored on disk and is thus persistent between invocations. The http-headers If-Modified-Since and ETag are used to let the server decide if the version in the cache is up-to-date or not. HTTP::Cache::Transparent was initially called HTTP::TransparentCache. It was renamed on request from modules@perl.org. ## Limitations This module has a number of limitations that you should be aware of before using it. They are documented in the POD-documentation for the module. ## Installation To install this module type the following: perl Makefile.PL make make test make install ## Dependencies - LWP - Storable (included with perl) - Digest::MD5 (included with perl) All http-requests are made through the LWP module. Data is stored on disk by the Storable module. Digest::MD5 is used for creating a hash of the url. ## Git repository A git repository with the sourcecode for HTTP::Cache::Transparent can be found at https://github.com/mattiash/HTTP-Cache-Transparent. ## Copyright and license Copyright (C) 2004-2017 by Mattias Holmlund This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. HTTP-Cache-Transparent-1.4/t/000755 000765 000024 00000000000 13071765072 016515 5ustar00mattiasstaff000000 000000 HTTP-Cache-Transparent-1.4/t/cache.t000644 000765 000024 00000005545 13071764554 017762 0ustar00mattiasstaff000000 000000 use strict; use warnings; use Test::More; use Test::RequiresInternet ('www.example.com' => 80); use File::Temp 'tempdir'; use LWP::Simple; use HTTP::Cache::Transparent; my $TMPDIR = undef; # URL of static web content to be retrieved. my $url = 'http://www.example.com'; # First locate some suitable tmp-dir. We need an absolute path. # Will be cleaned up once test has completed. for my $dir (tempdir( CLEANUP => 1 )) { if ( open(my $fh, '>', "$dir/test-$$")) { close($fh); unlink("$dir/test-$$"); $TMPDIR = $dir; last; } } if ( $TMPDIR ) { $TMPDIR =~ tr|\\|/|; plan tests => 8; } else { plan skip_all => 'Cannot test without a suitable TMP Directory'; } my $ua = LWP::UserAgent->new; # Create cache in temporary directory with a NoUpdate time of 10 secs HTTP::Cache::Transparent::init( { BasePath => $TMPDIR, NoUpdate => 10 } ); # Cache empty. Fetch the URL directly from the server my $r_init = $ua->get($url); # Check all headers are undef is (defined $r_init->header('X-Cached'), '', 'x-cached header should be undef when retrieving directly from server'); is (defined $r_init->header('X-Content-Unchanged'), '', 'x-content-unchanged header should be undef when retrieving directly from server'); is (defined $r_init->header('X-No-Server-Contact'), '', 'x-no-server-contact header should be undef when retrieving directly from server'); # URL Cached and within NoUpdate time. Fetching URL again should return directly from cache my $r_cached = $ua->get($url); # Check all headers are set is (defined $r_cached->header('X-Cached'), 1, 'x-cached header should be set when retrieving directly from cache'); is (defined $r_cached->header('X-Content-Unchanged'), 1, 'x-content-unchanged header should be set when retrieving directly from cache'); is (defined $r_cached->header('X-No-Server-Contact'), 1, 'x-no-server-contact header should be set when retrieving directly from cache'); # Wait for NoUpdate time to expire. sleep 10; # URL Cached but outside NoUpdate time. Server should be sent conditional GET before (unchanged) content is returned from cache my $r_server = $ua->get($url); # Check X-Cached & X-Content-Unchanged headers are set but X-No-Server-Contact is undef # Setting of X-Cached header apparently difficult to predict and seems to vary from ISP to ISP. Seems to interact with X-Cache header... #is (defined $r_server->header('X-Cached'), 1, 'x-cached header should be set when retrieving from cache after HTTP 304 from server'); is (defined $r_server->header('X-Content-Unchanged'), 1, 'x-content-unchanged header should be set when retrieving from cache after HTTP 304 from server'); is (defined $r_server->header('X-No-Server-Contact'), '', 'x-no-server-contact header should be undef when retrieving from cache after HTTP 304 from server'); HTTP-Cache-Transparent-1.4/t/HTTP-Cache-Transparent.t000644 000765 000024 00000000760 13057617114 022761 0ustar00mattiasstaff000000 000000 # Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl HTTP-Cache-Transparent.t' ######################### # change 'tests => 1' to 'tests => last_test_to_print'; use Test::More tests => 1; BEGIN { use_ok('HTTP::Cache::Transparent') }; ######################### # Insert your test code below, the Test::More module is use()ed here so read # its man page ( perldoc Test::More ) for help writing this test script. HTTP-Cache-Transparent-1.4/t/pod-coverage.t000644 000765 000024 00000000244 13057617114 021252 0ustar00mattiasstaff000000 000000 use Test::More; eval "use Test::Pod::Coverage 1.00"; plan skip_all => "Test::Pod::Coverage 1.00 required for testing POD coverage" if $@; all_pod_coverage_ok(); HTTP-Cache-Transparent-1.4/t/pod.t000644 000765 000024 00000000200 13057617114 017451 0ustar00mattiasstaff000000 000000 use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();HTTP-Cache-Transparent-1.4/lib/HTTP/000755 000765 000024 00000000000 13071765072 017577 5ustar00mattiasstaff000000 000000 HTTP-Cache-Transparent-1.4/lib/HTTP/Cache/000755 000765 000024 00000000000 13071765072 020602 5ustar00mattiasstaff000000 000000 HTTP-Cache-Transparent-1.4/lib/HTTP/Cache/Transparent.pm000644 000765 000024 00000034142 13071764624 023447 0ustar00mattiasstaff000000 000000 package HTTP::Cache::Transparent; use strict; our $VERSION = '1.4'; =head1 NAME HTTP::Cache::Transparent - Cache the result of http get-requests persistently. =head1 SYNOPSIS use LWP::Simple; use HTTP::Cache::Transparent; HTTP::Cache::Transparent::init( { BasePath => '/tmp/cache', } ); my $data = get( 'http://www.sn.no' ); =head1 DESCRIPTION An implementation of http get that keeps a local cache of fetched pages to avoid fetching the same data from the server if it hasn't been updated. The cache is stored on disk and is thus persistent between invocations. Uses the http-headers If-Modified-Since and ETag to let the server decide if the version in the cache is up-to-date or not. The cache is implemented by modifying the LWP::UserAgent class to seamlessly cache the result of all requests that can be cached. =head1 INITIALIZING THE CACHE HTTP::Cache::Transparent provides an init-method that sets the parameters for the cache and overloads a method in LWP::UserAgent to activate the cache.After init has been called, the normal LWP-methods (LWP::Simple as well as the more full-fledged LWP::Request methods) should be used as usual. =over 4 =cut use Carp; use LWP::UserAgent; use HTTP::Status qw/RC_NOT_MODIFIED RC_OK RC_PARTIAL_CONTENT status_message/; use Digest::MD5 qw/md5_hex/; use IO::File; use File::Copy; use File::Path; use Cwd; # These are the response-headers that we should store in the # cache-entry and recreate when we return a cached response. my @cache_headers = qw/Content-Type Content-Encoding Content-Length Content-Range Last-Modified/; my $basepath; my $maxage; my $verbose; my $noupdate; my $approvecontent; my $org_simple_request; =item init Initialize the HTTP cache. Takes a single parameter which is a hashref containing named arguments to the object. HTTP::Cache::Transparent::init( { # Directory to store the cache in. BasePath => "/tmp/cache", # How many hours should items be kept in the cache # after they were last requested? # Default is 8*24. MaxAge => 8*24, # Print progress-messages to STDERR. # Default is 0. Verbose => 1, # If a request is made for a url that has been requested # from the server less than NoUpdate seconds ago, the # response will be generated from the cache without # contacting the server. # Default is 0. NoUpdate => 15*60, # When a url has been downloaded and the response indicates that # has been modified compared to the content in the cache, # the ApproveContent callback is called with the HTTP::Response. # The callback shall return true if the response shall be used and # stored in the cache or false if the response shall be discarded # and the response in the cache used instead. # This mechanism can be used to work around servers that return errors # intermittently. The default is to accept all responses. ApproveContent => sub { return $_[0]->is_success }, } ); The directory where the cache is stored must be writable. It must also only contain files created by HTTP::Cache::Transparent. =cut my $initialized = 0; sub init { my( $arg ) = @_; defined( $arg->{BasePath} ) or croak( "You must specify a BasePath" ); $basepath = $arg->{BasePath}; if( not -d $basepath ) { eval { mkpath($basepath) }; if ($@) { print STDERR "$basepath is not a directory and cannot be created: $@\n"; exit 1; } } # Append a trailing slash if it is missing. $basepath =~ s%([^/])$%$1/%; $maxage = $arg->{MaxAge} || 8*24; $verbose = $arg->{Verbose} || 0; $noupdate = $arg->{NoUpdate} || 0; $approvecontent = $arg->{ApproveContent} || sub { return 1; }; # Make sure that LWP::Simple does not use its simplified # get-method that bypasses LWP::UserAgent. $LWP::Simple::FULL_LWP++; unless ($initialized++) { $org_simple_request = \&LWP::UserAgent::simple_request; no warnings; *LWP::UserAgent::simple_request = \&_simple_request_cache } } =item Initializing from use-line An alternative way of initializing HTTP::Cache::Transparent is to supply parameters in the use-line. This allows you to write use HTTP::Cache::Transparent ( BasePath => '/tmp/cache' ); which is exactly equivalent to use HTTP::Cache::Transparent; HTTP::Cache::Transparent::init( BasePath => '/tmp/cache' ); The advantage to using this method is that you can do perl -MHTTP::Cache::Transparent=BasePath,/tmp/cache myscript.pl or even set the environment variable PERL5OPT PERL5OPT=-MHTTP::Cache::Transparent=BasePath,/tmp/cache myscript.pl and have all the http-requests performed by myscript.pl go through the cache without changing myscript.pl =back =cut sub import { my( $module, %args ) = @_; return if (scalar(keys(%args)) == 0); HTTP::Cache::Transparent::init( \%args ); } END { _remove_old_entries(); } sub _simple_request_cache { my($self, $r, $content_cb, $read_size_hint) = @_; my $res; if( $r->method eq "GET" and not defined( $r->header( 'If-Modified-Since' ) ) and not defined( $content_cb ) ) { print STDERR "Fetching " . $r->uri if( $verbose ); my $url = $r->uri->as_string; my $key = $url; $key .= "\n" . $r->header('Range') if defined $r->header('Range'); my $filename = $basepath . _urlhash( $url ); my $fh; my $meta; if( -s $filename ) { $fh = new IO::File "< $filename" or die "Failed to read from $filename"; $meta = _read_meta( $fh ); if( $meta->{Url} eq $url ) { $meta->{'Range'} = "" unless defined( $meta->{'Range'} ); # Check that the Range is the same for this request as # for the one in the cache. if( (not defined( $r->header( 'Range' ) ) ) or $r->header( 'Range' ) eq $meta->{'Range'} ) { $r->header( 'If-Modified-Since', $meta->{'Last-Modified'} ) if exists( $meta->{'Last-Modified'} ); $r->header( 'If-None-Match', $meta->{ETag} ) if( exists( $meta->{ETag} ) ); } } else { warn "Cache collision: $url and $meta->{Url} have the same md5sum"; } } if( defined( $meta->{'X-HCT-LastUpdated'} ) and $noupdate > (time - $meta->{'X-HCT-LastUpdated'} ) ) { print STDERR " from cache without checking with server.\n" if $verbose; $res = HTTP::Response->new( $meta->{Code} ); $res->request($r); _get_from_cachefile( $filename, $fh, $res, $meta ); $fh->close() if defined $fh;; # Set X-No-Server-Contact header as content delivered without contact with external server $res->header( "X-No-Server-Contact", 1 ); return $res; } $res = &$org_simple_request( $self, $r ); if( $res->code == RC_NOT_MODIFIED ) { print STDERR " from cache.\n" if( $verbose ); _get_from_cachefile( $filename, $fh, $res, $meta ); $fh->close() if defined $fh;; # We need to rewrite the cache-entry to update X-HCT-LastUpdated _write_cache_entry( $filename, $url, $r, $res ); return $res; } elsif( defined( $meta->{'X-HCT-LastUpdated'} ) and not &{$approvecontent}( $res ) ) { print STDERR " from cache since the response was not approved.\n" if( $verbose ); _get_from_cachefile( $filename, $fh, $res, $meta ); $fh->close() if defined $fh;; # Do NOT update the cache! return $res; } else { $fh->close() if defined $fh;; my $content = $res->content; $content = "" if not defined $content; if( defined( $meta->{MD5} ) and md5_hex( $content ) eq $meta->{MD5} ) { $res->header( "X-Content-Unchanged", 1 ); print STDERR " unchanged" if( $verbose ); } print STDERR " from server.\n" if( $verbose ); _write_cache_entry( $filename, $url, $r, $res ) if( $res->code == RC_OK or $res->code == RC_PARTIAL_CONTENT ); } } else { # We won't try to cache this request. $res = &$org_simple_request( $self, $r, $content_cb, $read_size_hint ); } return $res; } sub _get_from_cachefile { my( $filename, $fh, $res, $meta ) = @_; my $content; my $buf; while ( $fh->read( $buf, 1024 ) > 0 ) { $content .= $buf; } $fh->close(); $content = "" if not defined $content; # Set last-accessed for cache-entry. my $mtime = time; utime( $mtime, $mtime, $filename ); # modify response if( $HTTP::Message::VERSION >= 1.44 ) { $res->content_ref( \$content ); } else { $res->content( $content ); } # For HTTP::Cache::Transparent earlier than 0.4, # there is no Code in the cache. if( defined( $meta->{Code} ) ) { $res->code( $meta->{Code} ); } else { $res->code( RC_OK ); } $res->message(status_message($res->code) || "Unknown code"); foreach my $h (@cache_headers) { $res->header( $h, $meta->{$h} ) if defined( $meta->{ $h } ); } $res->header( "X-Cached", 1 ); $res->header( "X-Content-Unchanged", 1 ); } # Read metadata and position filehandle at start of data. sub _read_meta { my( $fh ) = @_; my %meta; my( $key, $value ); do { my $line = <$fh>; ( $key, $value ) = ($line =~ /(\S+)\s+(.*)[\n\r]*/); $meta{$key} = $value if( defined $value ); } while( defined( $value ) ); return \%meta; } # Write metadata and position filehandle where data should be written. sub _write_meta { my( $fh, $meta ) = @_; foreach my $key (sort keys( %{$meta} ) ) { print $fh "$key $meta->{$key}\n"; } print $fh "\n"; } sub _write_cache_entry { my( $filename, $url, $req, $res ) = @_; my $out_filename = "$filename.tmp$$"; my $fh = new IO::File "> $out_filename" or die "Failed to write to $out_filename"; my $meta; $meta->{Url} = $url; $meta->{ETag} = $res->header('ETag') if defined( $res->header('ETag') ); my $content = $res->content; $content = "" if not defined $content; $meta->{MD5} = md5_hex( $content ); $meta->{Range} = $req->header('Range') if defined( $req->header('Range') ); $meta->{Code} = $res->code; $meta->{'X-HCT-LastUpdated'} = time; foreach my $h (@cache_headers) { $meta->{$h} = $res->header( $h ) if defined $res->header( $h ); } _write_meta( $fh, $meta ); print $fh $content; $fh->close; move( $out_filename, $filename ) || unlink $out_filename; } sub _urlhash { my( $url ) = @_; return md5_hex( $url ); } sub _remove_old_entries { if( defined( $basepath ) and -d( $basepath ) ) { my $oldcwd = getcwd(); chdir( $basepath ); my @files = glob("*"); foreach my $file (@files) { if( $file !~ m%^[0-9a-f]{32}$% ) { print STDERR "HTTP::Cache::Transparent: Unknown file found in cache directory: $basepath$file\n"; } else { my $age = (-M $file); # The file may have disappeared if another process has cleaned # the cache. if( defined($age) && ( $age*24 > $maxage ) ) { print STDERR "Deleting $file.\n" if( $verbose ); unlink( $file ); } } } chdir( $oldcwd ); } } =head1 INSPECTING CACHE BEHAVIOR The HTTP::Cache::Transparent inserts three special headers in the HTTP::Response object. These can be accessed via the HTTP::Response::header()-method. =over 4 =item X-Cached This header is inserted and set to 1 if the response is delivered from the cache instead of from the server. =item X-Content-Unchanged This header is inserted and set to 1 if the content returned is the same as the content returned the last time this url was fetched. This header is always inserted and set to 1 when the response is delivered from the cache. =item X-No-Server-Contact This header is inserted and set to 1 if the content returned has been delivered without any contact with the external server, i.e. no conditional or unconditional HTTP GET request has been sent, the content has been delivered directly from cache. This may be useful when seeking to control loading of the external server. =back =head1 LIMITATIONS This module has a number of limitations that you should be aware of before using it. =over 4 =item - There is no upper limit to how much diskspace the cache requires. The only limiting mechanism is that data for urls that haven't been requested in the last MaxAge hours will be removed from the cache the next time the program exits. =item - Currently, only get-requests that store the result in memory (i.e. do not use the option to have the result stored directly in a file or delivered via a callback) is cached. I intend to remove this limitation in a future version. =item - The support for Ranges is a bit primitive. It creates a new object in the cache for each unique combination of url and range. This will work ok as long as you always request the same range(s) for a url. =item - The cache doesn't properly check and store all headers in the HTTP request and response. Therefore, if you request the same url repeatedly with different sets of headers (cookies, accept-encoding etc), and these headers affect the response from the server, the cache may return the wrong response. =item - HTTP::Cache::Transparent has not been tested with threads, and will most likely not work if you use them. =back =head1 CACHE FORMAT The cache is stored on disk as one file per cached object. The filename is equal to the md5sum of the url and the Range-header if it exists. The file contains a set of key/value-pairs with metadata (one entry per line) followed by a blank line and then the actual data returned by the server. The last modified date of the cache file is set to the time when the cache object was last requested by a user. =head1 AUTHOR Mattias Holmlund, E$firstname -at- $lastname -dot- seE L =head1 GIT REPOSITORY A git repository containing the source for this module can be found via http://git.holmlund.se/ =head1 COPYRIGHT AND LICENSE Copyright (C) 2004-2007 by Mattias Holmlund This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available. =cut 1; HTTP-Cache-Transparent-1.4/examples/check_server000755 000765 000024 00000002712 13057617114 022460 0ustar00mattiasstaff000000 000000 #!/usr/bin/perl -w use strict; use LWP::Simple; use HTTP::Cache::Transparent; if( scalar( @ARGV ) != 1 ) { print << "EOD"; usage: check_server Fetches a url via the HTTP::Cache::Transparent module in verbose mode. The url is fetched twice to see if the server supports caching or not. The first line of output will say that the url is fetched from the server (unless you have fetched this url before and it is already in the cache). The second line of output will tell you what happened when we tried to fetch the same url a second time: Fetching ... from server: The server returned a new page that was different from the page that was fetched the previous time. Caching didn't improve anything. Fetching ... unchanged from server: The server indicated that caching was not possible, but still returned the exact same page as the last time. Caching didn't improve anything. Fetching ... from cache: The server returned a short note saying that the contents of the cache was still up-to-date. If the page was big, the cache saved us a lot of bandwidth. The cache is stored in the directory /tmp/cache. This directory must exist and be empty before the command is run. EOD exit; } my( $url ) = @ARGV; HTTP::Cache::Transparent::init( { BasePath => "/tmp/cache", # Directory to store the cache in. Verbose => 1, # Print messages to STDERR. Default is 0. } ); # Fetch once my $data = get( $url ); # and twice. $data = get( $url ); HTTP-Cache-Transparent-1.4/examples/check_server_approve000755 000765 000024 00000001223 13057617114 024210 0ustar00mattiasstaff000000 000000 #!/usr/bin/perl -w use strict; use LWP::Simple; use HTTP::Cache::Transparent; if( scalar( @ARGV ) != 1 ) { print << "EOD"; usage: check_server Fetches a url via the HTTP::Cache::Transparent module in verbose mode. Uses an ApproveContent sub that only approves responses with a successful response-code. EOD exit; } my( $url ) = @ARGV; HTTP::Cache::Transparent::init( { BasePath => "/tmp/cache", # Directory to store the cache in. Verbose => 1, # Print messages to STDERR. Default is 0. NoUpdate => 0, ApproveContent => sub { return $_[0]->is_success(); }, } ); # Fetch once my $data = get( $url ); print $data; HTTP-Cache-Transparent-1.4/examples/test-range000755 000765 000024 00000004224 13057617114 022066 0ustar00mattiasstaff000000 000000 #!/usr/bin/perl -w # Copyright (C) 2002 Nigel Horne # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. use strict; use WWW::RobotRules::AnyDBM_File; use LWP::RobotUA; # for spidering and cache lookup use HTTP::Cache::Transparent; HTTP::Cache::Transparent::init( { BasePath => '/tmp/cache', Verbose => 1 } ); my $url = "http://www.bandsman.co.uk"; my $rules = WWW::RobotRules::AnyDBM_File->new('www.bandsman.co.uk/Spider', '/tmp/robots.cache'); my $robot = LWP::RobotUA->new('www.bandsman.co.uk/Spider', 'njh@despammed.com', $rules); $robot->timeout(20); # $robot->delay(1/60); # wait 1 second between accesses to same site $robot->delay(0); $robot->protocols_allowed(['http']); # disabling all others my $request = new HTTP::Request 'GET' => $url; $request->header('Accept' => 'text/html'); $robot->max_size(2048); $request->header('Accept-Encoding' => 'gzip; deflate', 'Referer' => 'http://www.bandsman.co.uk'); my $webdoc = $robot->simple_request($request); if(!$webdoc->is_success) { die $webdoc->status_line . "\n"; exit 1; } my $content = $webdoc->content; if(my $encoding = $webdoc->content_encoding) { if($encoding =~ /gzip/i) { $content = Compress::Zlib::memGunzip($content); if(!defined $content) { die "$url can't be gunziped\n"; } } elsif($encoding =~ /deflate/i) { $content = Compress::Zlib::uncompress($content); if(!defined $content) { die "$url can't be uncompressed\n"; } } } print "$url: " . length($content) . " bytes\n"; print $content . "\n";