]> Sergey Matveev's repositories - public-inbox.git/blob - public-inbox.cgi
www: enable and expand preload from mod_perl2
[public-inbox.git] / public-inbox.cgi
1 #!/usr/bin/perl -w
2 # Copyright (C) 2014, Eric Wong <normalperson@yhbt.net> and all contributors
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
4 use strict;
5 use warnings;
6 use IO::Handle;
7 use PublicInbox::WWW;
8 use CGI qw/-nosticky/;
9 our $NO_SCRIPT_NAME;
10 our %HTTP_CODES;
11 BEGIN {
12         $NO_SCRIPT_NAME = 1 if $ENV{NO_SCRIPT_NAME};
13         if ($ENV{MOD_PERL}) {
14                 CGI->compile;
15                 PublicInbox::WWW->preload;
16         }
17
18         %HTTP_CODES = (
19                 200 => 'OK',
20                 301 => 'Moved Permanently',
21                 404 => 'Not Found',
22                 405 => 'Method Not Allowed',
23                 501 => 'Not Implemented',
24         );
25 }
26
27 # some servers (Ruby webrick) include scheme://host[:port] here,
28 # which confuses CGI.pm when generating self_url.
29 # RFC 3875 does not mention REQUEST_URI at all,
30 # so nuke it since CGI.pm functions without it.
31 delete $ENV{REQUEST_URI};
32 $ENV{SCRIPT_NAME} = '' if $NO_SCRIPT_NAME;
33 my $req = CGI->new;
34 my $ret = PublicInbox::WWW::run($req, $req->request_method);
35
36 my $out = select;
37 $out->binmode;
38
39 if (ref($ret) eq 'CODE') {
40         $ret->(*dump_header);
41 } else {
42         my ($status, $headers, $body) = @$ret;
43
44         dump_header([$status, $headers])->write($body->[0]);
45 }
46
47 sub dump_header {
48         my ($res) = @_;
49         my $fh = select;
50         my ($status, $headers) = @$res;
51         $fh->write("Status: $status $HTTP_CODES{$status}\r\n");
52         my @tmp = @$headers;
53         while (my ($k, $v) = splice(@tmp, 0, 2)) {
54                 $fh->write("$k: $v\r\n");
55         }
56         $fh->write("\r\n");
57         $fh;
58 }