使用Perl构建Web服务

smi*_*ith 5 perl web-services

我需要构建一个服务器端应用程序(小型Web服务)来测试建议.有哪些CPAN模块和Perl库可用于实现此类任务?

dgw*_*dgw 5

有很多可能性

  • CGI - 如果你喜欢像过去那样做任何事
  • CGI::Application - 更高级一点

或者你可以使用像这样的框架

  • Catalyst
  • Dancer
  • Mojolicious

这取决于您的技能和目标,您应该选择什么解决方案。


dax*_*xim 5

使用Plack :: Test测试一个小型Web服务:

use Plack::Test;
use Test::More;
test_psgi(
    app => sub {
        my ($env) = @_;
        return [200, ['Content-Type' => 'text/plain'], ["Hello World"]],
    },
    client => sub {
        my ($cb) = @_;
        my $req  = HTTP::Request->new(GET => "http://localhost/hello");
        my $res  = $cb->($req);
        like $res->content, qr/Hello World/;
    },
);
done_testing;
Run Code Online (Sandbox Code Playgroud)


Ale*_*lds 5

Web服务只返回HTTP状态代码和一些数据,可能是用JSON或XML序列化的.您可以使用该CGI模块执行此操作,例如:

#!/usr/bin/perl -w

use strict;
use warnings;
use CGI;
use CGI::Pretty qw/:standard/;
use URI::Escape;

my $query = CGI->new;
my $jsonQueryValue = uri_unescape $query->param('helloWorld'); 

#  let's say that 'helloWorld' is a uri_escape()-ed POST variable 
#  that contains the JSON object { 'hello' : 'world' }

print header(-type => "application/json", -status => "200 OK");
print "$jsonQueryValue";
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用其他状态代码和数据打印HTTP响应.例如,Web服务可能需要返回404错误,具体取决于要求的内容.诸如此类的事情.