|
Revision 24403, 2.4 kB
(checked in by tokuhirom, 5 years ago)
|
|
MENTA::Dispatch に分離
|
| Line | |
|---|
| 1 | package MENTA::Dispatch; |
|---|
| 2 | use strict; |
|---|
| 3 | use warnings; |
|---|
| 4 | use utf8; |
|---|
| 5 | |
|---|
| 6 | sub dispatch { |
|---|
| 7 | my $path = $ENV{PATH_INFO} || '/'; |
|---|
| 8 | $path =~ s!^/+!!g; |
|---|
| 9 | if ($path =~ /^[a-z0-9_]*$/) { |
|---|
| 10 | $path ||= 'index'; |
|---|
| 11 | my $cdir = main::controller_dir(); |
|---|
| 12 | my $controller = "${cdir}/${path}.pl"; |
|---|
| 13 | my $controller_mt = "${cdir}/${path}.mt"; |
|---|
| 14 | if (-f $controller) { |
|---|
| 15 | my $meth = "do_$path"; |
|---|
| 16 | package main; |
|---|
| 17 | do $controller; |
|---|
| 18 | if (my $e = $@) { |
|---|
| 19 | if (ref $e) { |
|---|
| 20 | return; |
|---|
| 21 | } else { |
|---|
| 22 | die $e; |
|---|
| 23 | } |
|---|
| 24 | } |
|---|
| 25 | die $@ if $@; |
|---|
| 26 | if (my $code = main->can($meth)) { |
|---|
| 27 | $code->(); |
|---|
| 28 | die "なにも出力してません"; |
|---|
| 29 | } else { |
|---|
| 30 | die "「${path}」というモードは存在しません!${controller} の中に ${meth} が定義されていないようです"; |
|---|
| 31 | } |
|---|
| 32 | } elsif (-f $controller_mt) { |
|---|
| 33 | my $out = main::__render_partial("${path}.mt", main::controller_dir()); |
|---|
| 34 | utf8::encode($out); |
|---|
| 35 | print "Content-Type: text/html; charset=utf-8\r\n"; |
|---|
| 36 | print "\r\n"; |
|---|
| 37 | print $out; |
|---|
| 38 | } else { |
|---|
| 39 | die "「${path}」というモードは存在しません。コントローラファイルもありません(${controller})。テンプレートファイルもありません(${controller_mt})"; |
|---|
| 40 | } |
|---|
| 41 | } elsif ($path ne 'menta.cgi' && -f "app/$path" && $path =~ /^static\//) { |
|---|
| 42 | show_static("app/$path"); |
|---|
| 43 | } elsif ($path =~ /^(?:crossdomain\.xml|favicon\.ico|robots\.txt)$/) { |
|---|
| 44 | print "status: 404\r\ncontent-type: text/plain\r\n\r\n"; |
|---|
| 45 | } else { |
|---|
| 46 | die "${path} を処理する方法がわかりません"; |
|---|
| 47 | } |
|---|
| 48 | } |
|---|
| 49 | |
|---|
| 50 | sub show_static { |
|---|
| 51 | my $path = shift; |
|---|
| 52 | open my $fh, '<', $path or die "ファイルを開けません: ${path}: $!"; |
|---|
| 53 | binmode $fh; |
|---|
| 54 | binmode STDOUT; |
|---|
| 55 | printf "Content-Type: %s\r\n\r\n", guess_mime_type($path); |
|---|
| 56 | print do { local $/; <$fh> }; |
|---|
| 57 | close $fh; |
|---|
| 58 | } |
|---|
| 59 | |
|---|
| 60 | sub guess_mime_type { |
|---|
| 61 | my $ext = shift; |
|---|
| 62 | $ext =~ s/.+\.(.+)$/$1/; |
|---|
| 63 | |
|---|
| 64 | # TODO should be moved to other. |
|---|
| 65 | my $mime_map = { |
|---|
| 66 | css => 'text/css', |
|---|
| 67 | js => 'application/javascript', |
|---|
| 68 | jpg => 'image/jpeg', |
|---|
| 69 | gif => 'image/gif', |
|---|
| 70 | png => 'image/png', |
|---|
| 71 | txt => 'text/plain', |
|---|
| 72 | }; |
|---|
| 73 | $mime_map->{$ext} || 'application/octet-stream'; |
|---|
| 74 | } |
|---|
| 75 | |
|---|
| 76 | "END OF MODULE"; |
|---|