I am trying to use a CGI script to act as static provider for my application assets. Since I am relatively new to Perl, I don’t think my code is the best way to achieve what I want. If you have better code, let me know. Here’s my recent script
#!/usr/bin/perl
use lib "/usr/share/perl/5.10.1";
$asset_path = "/home/foo/public_html/assets/img/";
$uri_asset_path = "http://v2.foo.com/assets/img/";
use File::stat;
use Time::localtime;
$ENV{QUERY_STRING}=~ s/:/\//g;
$file = $asset_path . $ENV{QUERY_STRING};
unless (-e $file) {
print header('text/html','404 Not Found');
exit();
}
$raw_last_modified = ctime(stat($file)->mtime);
$age = 30*24*60*60;
$date_day = substr $raw_last_modified, 0, 3;
$date_mon = substr $raw_last_modified, 4, 3;
$date_mon = substr $raw_last_modified, 4, 3;
$date_d = substr $raw_last_modified, 8, 2;
$date_time = substr $raw_last_modified, 11, 8;
$date_year = substr $raw_last_modified, 20, 4;
$last_modified = "$date_day, $date_d $date_mon $date_year $date_time GMT";
use CGI qw/:standard/;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $response = $ua->get("$uri_asset_path/$ENV{QUERY_STRING}");
unless ($response->is_success){
print header('text/html','404 Not Found');
exit();
}
if(defined($ENV{'HTTP_IF_MODIFIED_SINCE'})){
if ($ENV{'HTTP_IF_MODIFIED_SINCE'} == $last_modified){
print header('text/html','304 Not Modified');
return();
}
}
print header(-type=>'image/png',-expires=>'+30d',-last_modified => $last_modified,-cache_control => 'max-age='.$age.', must-revalidate');
print $response->content;
Thanks.
It does not look like you have a specific question. I am assuming you are soliciting advice on how to write a CGI script properly.
I do not see why there is any need to write a CGI script for this. Just configure your web server properly to add
expiresand Etag information.You should add
use warnings;anduse strict;to your script, run it in ‘taint’ mode, not use$ENV{QUERY_STRING}directly, but access variables provided usingCGI.pm‘sparammethod etc.I do not understand why
LWP::UserAgentmakes an appearance, why you are issuing aGET.Perhaps you can explain why you are doing what you are doing and formulate a specific question in line with the Q&A nature of this site.
In addition, you might want to read How (and how not) to Control Caches.