有没有办法在舞者中有一个应用程序但有多个应用程序目录。
或者我可以做这样的事情:
我的项目在目录'foo'中。假设我有一个目录'bar'(不在'foo'内),它有一个名为'public'的目录。我的应用程序“foo”将此公众用作自己的公众,如果它搜索让我们说“/css/style.css”并且它不在“/bar/public/”中,它应该搜索“/foo/”上市/'。我怎样才能做到这一点?
好的,这是一个很好的方法。它当然可以是一个插件。
你不应该通过入侵 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
编写呈现静态(并替换某些功能)的插件的方法之一。您可以使用Dancer::Plugin::Thumbnail作为示例。
我看到的另一种方法是get_file_response()
在Dancer::Renderer进行猴子补丁,这并不是一个好主意。
@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 配置来为您完成这项工作。
这个模块可能对你有帮助吗? https://github.com/Perlover/Dancer-Plugin-Hosts 您可以使用自己的 appdir 和其他目录设置在 Dancer 中设置虚拟站点 我今天将此模块上传到 github 很快将在 CPAN 中