有没有办法让一个应用程序在舞者中,但有多个appdirs。
或者我可以这样做:
我的项目是dir'foo'。让我们说我有一个dir'bar'(不在'foo'里面),它有一个名为'public'的目录。我的应用程序'foo'使用这个公众作为自己的公众,如果它搜索让我们说'/css/style.css'并且它不在'/ bar / public /'它应该搜索'/ foo /上市/'。我怎么能这样做?
答案 0 :(得分:7)
好的,这是做这件事的好方法。它当然可以是一个插件。
你不应该通过黑客入侵Dancer的核心来做这种事情,你应该总是考虑实施一个路由处理程序来完成这项工作:
#!/usr/bin/env perl
use Dancer;
use File::Spec;
use Dancer::FileUtils 'read_file_content';
use Dancer::MIME;
use HTTP::Date;
# your routes here
# then the catchall route for
# serving static files
# better in config
my @public_dirs = qw(/tmp/test/foo /tmp/test/bar /tmp/test/baz);
get '/**' => sub {
my $path = request->path;
my $mime = Dancer::MIME->instance;
# security checks
return send_error("unauthrorized request", 403) if $path =~ /\0/;
return send_error("unauthrorized request", 403) if $path =~ /\.\./;
# decompose the path_info into a file path
my @path = split '/', $path;
for my $location (@public_dirs) {
my $file_path = File::Spec->catfile($location, @path);
next if ! -f $file_path;
my $content = read_file_content($file_path);
my $content_type = $mime->for_file($file_path);
my @stat = stat $file_path;
header 'Content-Type', $content_type;
header 'Content-Length', $stat[7];
header 'Last-Modified', HTTP::Date::time2str($stat[9]);
return $content;
}
pass;
};
start;
此应用运行的一个示例:
$ mkdir -p /tmp/test/foo /tmp/test/bar /tmp/test/baz
$ echo 1 > /tmp/test/foo/foo.txt
$ echo 2 > /tmp/test/bar/bar.txt
$ echo 3 > /tmp/test/baz/baz.txt
$ ./bin/app.pl
$ curl -I http://0:3000/baz.txt
HTTP/1.0 200 OK
Content-Length: 2
Content-Type: text/plain
Last-Modified: Fri, 14 Oct 2011 11:28:03 GMT
X-Powered-By: Perl Dancer 1.3051
答案 1 :(得分:2)
编写呈现静态(并替换某些功能)的插件的方法之一。您可以使用Dancer::Plugin::Thumbnail作为示例。
我看到的另一种方法是在Dancer::Renderer进行猴子补丁get_file_response()
这不是一个好主意。
以下代码在@dirs
数组的每个目录中查找静态文件。它很脏,很丑,不安全。
这可以在将来的版本中打破,并可能导致我不熟悉的Dancer框架的其他部分出现问题。你被警告了。
#!/usr/bin/env perl
use Dancer;
use Dancer::Renderer;
use MyWeb::App;
my $get_file_response_original = \&Dancer::Renderer::get_file_response;
my @dirs = ('foo');
*Dancer::Renderer::get_file_response = sub {
my $app = Dancer::App->current;
my $result;
# Try to find static in default dir
if ($result = $get_file_response_original->(@_)) {
return $result;
}
# Save current settings
my $path_backup = $app->setting('public');
# Go through additional dirs
foreach my $dir (@dirs) {
$app->setting(public => $dir);
if ($result = $get_file_response_original->(@_)) {
last;
}
}
# Restore public
$app->setting('public' => $path_backup);
return $result
};
dance;
第三种方法是让nginx通过为你的应用程序编写适当的nginx配置来为你工作。
答案 2 :(得分:-1)