我正在尝试在Perl中实现RESTful API。我当前的想法是简单地使用正则表达式解析path_info,然后将请求分派(dispatch)到适当的子例程,然后该子例程将为请求的资源吐出JSON,XML甚至XHTML。
例如,要检索有关用户1234的信息,RESTful客户端应在以下位置找到它:
http://example.com/model.pl/users/1234
以下是我第一次尝试实现RESTful API的框架代码:
model.pl :
#!/usr/bin/perl -w
use strict;
use CGI;
my $q = CGI->new();
print $q->header('text/html');
my $restfuluri = $q->path_info;
if ($restfuluri =~ /^\/(questions)\/([1-9]+$)/) { questions($1, $2); }
elsif ($restfuluri =~ /^\/(users)\/([1-9]+$)/) { users($1, $2); }
sub questions
{
my $object = shift;
my $value = shift;
#This is a stub, spits out JSON or XML when implemented.
print $q->p("GET question : $object -> $value");
}
sub users
{
my $object = shift;
my $value = shift;
#This is a stub, spits out JSON or XML when implemented.
print $q->p("GET user: $object -> $value");
}
在继续进行下一步之前,我想听听经验丰富的Perl黑客是否对我的基本思想正确,以及这种方法在性能方面是否存在严重缺陷。
我可以想象,一段时间后,if/else块会变得非常大。
期待听到您的意见,以使此代码更好。
最佳答案
我将使用类似CGI::Application::Dispatch的工具,它使我可以使用变量和REST方法构建调度表,并允许您使用CPAN的CGI和CGI::Application模块。例如。:
table => [
'/questions/:id[get]' => { rm => 'get_question' },
'/users/:id[get]' => { rm => 'get_user' }, # OR
':app/:id[post]' => { rm => 'update' }, # where :app is your cgi application module
':app/:id[delete]' => { rm => 'delete' },
],
(或者您可以使用auto_rest或auto_rest_lc)
您可以为每种类型的事物使用单独的CGI::Application类(或仅在cgi-app Controller 类方法中使用类)。
CGI::Application还带有用于输出XML,JSON或从模板生成的文本的插件。
cgi-app(和c::a::d)是CGI应用程序,可以在CGI,FastCGI或mod_perl下使用(很少或不更改)使用。 C::A::D也是默认情况下的mod_perl PerlHandler。