views:

39

answers:

1

I'm trying to figure out the right way to serve icon files for our site listings. Basically an icon for a listing can come from an image file from a handful of different services (Flickr, Picasa, Google Static Maps, our own internal image hosting service, etc). The URL of the icon is stored in our database so I'd like to enable each listing icon to be displayed by simply calling:

http://www.example.com/listing/1234/icon

Currently I have been using CGI.pm to do a redirect to the correct icon URL, however, I want the file to be directly displayed without having to do a 301 redirect. Here is the code for what we've been using:

my $url = "http://www.example-service.com/image-123.gif";
print $query->redirect(-url=>$url);

I would appreciate any suggestions and code examples of on how I could update this to serve the file via proxy without having to redirect the user. Thanks in advance for your help!

+1  A: 

Use LWP to get the remote file and print it out.

#!/usr/local/bin/perl
use LWP::UserAgent;
use CGI;
my $q = CGI->new;
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1");
my $url = 'http://www.example-service.com/image-123.gif';

# Create a request
my $req = HTTP::Request->new(GET => $url);

my $res = $ua->request($req);

if ($res->is_success) {
        print $q->header( $res->content_type );
        print $res->content;
} else {
        print $q->header( 'text/plain', $res->status_line );
        print $res->status_line, "\n";
}

Alternatively you could write a trigger for your database which downloads the image for the listing and stores it either in the webroot somewhere or in the database itself when you add a new listing.

MkV
Is there no easier way? We already do something similar to this in our .htaccess file with a 1-liner but that is only serving as a proxy for a single service so there is no need for the database query to get the correct URL. Is there no equivalent in Perl that allows you to simply act as a proxy for the request instead of needing to download and then serve the content?
Russell C.
Russell, this is exactly what a (network) proxy does.
daxim
@MkV @daxim - What about using an Apache RewriteMap in conjunction with a perl script to return the appropriate URL? Would that work and why would one be a better option than another?
Russell C.
If you use a RewriteMap, it would work, but it would be the equivalent of your previous code, sending a redirect to the image, not the content.
MkV