1 # It's just a little bit of perl, so hang tight if you're a php/etc user :)
5 # Import the MogileFS client and a helper util from Plack.
9 my $TRACKERS = ['tracker1:7001'];
12 # Initialize the client when the server starts.
13 # You could also do this in the middle of the request.
14 my $mogc = MogileFS::Client->new(domain => $DOMAIN,
18 # Request object for reading paths/cookies/etc.
21 # Only support GET requests for this example.
22 # Nothing stops us from supporting HEAD requests, though.
23 if ($req->method ne 'GET') {
24 return [ 403, [ 'Content-Type' => 'text/plain' ],
25 [ 'Only GET methods allowed' ] ];
28 # Pull out the GET /whatever path.
29 my $file = $req->path_info;
31 # At this stage you would do some validation, or query your own
32 # application database for what the MogileFS path actually is. In this
33 # example we just ensure there is a limited set of characters used.
34 unless ($file =~ m/^[A-Z0-9.\/\\]+$/gmi) {
35 return [ 404, [ 'Content-Type' => 'text/plain' ],
36 [ 'Invalid request format received!' ] ];
39 # Ask the MogileFS tracker for the paths to this file.
40 # At this point you could check memcached for cached paths as well, and
41 # cache if none were found.
42 my @paths = $mogc->get_paths($file);
44 # If MogileFS returns no paths, the file is likely missing or never
47 return [ 404, [ 'Content-Type' => 'text/plain' ],
48 [ 'File not found: ' . $file ] ];
51 # Now we create the magic Perlbal header, "X-REPROXY-URL". This header
52 # tells Perlbal to go fetch and return the file from where MogileFS has
54 # At this point you would add any other headers. If it's a jpeg, you would
55 # ship the proper 'image/jpeg' Content-Type. In this example we blanket
56 # serve everything as text/plain.
57 my $headers = [ 'Content-Type' => 'text/plain',
58 'X-REPROXY-URL' => join(' ', @paths) ];
60 # Return a 200 OK, the headers, and no body. The body will be filled in
61 # with what Perlbal fetches.
62 return [ 200, $headers, [ ] ];
65 # Some simple Plack glue, you can ignore this.
66 # For a real app you should use a full framework. ;)
69 my $req = Plack::Request->new($env);