Skip to content

Commit

Permalink
Merge pull request #2 from losomo/master
Browse files Browse the repository at this point in the history
Decoding utf-8 encoded parameters
  • Loading branch information
zby committed Aug 2, 2012
2 parents b3e12c9 + 66d0575 commit 0221962
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/WebNano/Controller.pm
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package WebNano::Controller;

use URI::Escape 'uri_unescape';
use Plack::Request;
use Encode;

use WebNano::FindController 'find_nested';
use Object::Tiny::RW qw/ app env self_url url_map _req path /;
Expand All @@ -15,6 +16,8 @@ sub req {
my $self = shift;
return $self->_req if defined $self->_req;
my $req = Plack::Request->new( $self->env );
_decode_parameters($req->query_parameters);
_decode_parameters($req->body_parameters);
$self->_req( $req );
return $req;
}
Expand Down Expand Up @@ -92,6 +95,15 @@ sub handle {

sub search_subcontrollers { 0 }

sub _decode_parameters {
my ($multihash) = @_;
for my $key (keys %$multihash) {
my @vals = $multihash->get_all($key);
$multihash->remove($key);
$multihash->set(decode_utf8($key), map decode_utf8($_), @vals);
}
}

1;

__END__
Expand Down
60 changes: 60 additions & 0 deletions t/utf8.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use strict;
use warnings;

use Test::More;
use Plack::Test;
use HTTP::Request::Common;
use Encode;
use URI::Escape;
use utf8;

my $PLAIN_TEST_KEY = 'param1';
my $UTF_TEST_KEY = '키스의 고유조건은 입술끼리 만나야 하고 특별한 기술은 필요치 않다';
my $UTF_TEST_VALUE = 'Příliš žluťoučký kůň úpěl ďábelské ódy';

test_psgi(
app => MyApp->new()->psgi_app,
client => sub {
my $cb = shift;
my $res = $cb->(POST "http://localhost/", [$PLAIN_TEST_KEY => $UTF_TEST_VALUE]);
is(decode_utf8($res->content), $UTF_TEST_VALUE, 'UTF-8 values in POSTed form');
}
);

test_psgi(
app => MyApp->new()->psgi_app,
client => sub {
my $cb = shift;
my $res = $cb->(POST "http://localhost/", [$UTF_TEST_KEY => $UTF_TEST_VALUE]);
is(decode_utf8($res->content), $UTF_TEST_VALUE, 'UTF-8 keys and values in POSTed form');
}
);

test_psgi(
app => MyApp->new()->psgi_app,
client => sub {
my $cb = shift;
my $res = $cb->(GET "http://localhost/?" . uri_escape_utf8($UTF_TEST_KEY) . '=' . uri_escape_utf8($UTF_TEST_VALUE));
is(decode_utf8($res->content), $UTF_TEST_VALUE, 'UTF-8 values as GET parameters');
}
);

done_testing;

{
package MyApp;
use base 'WebNano';
1;
}

{
package MyApp::Controller;
use base 'WebNano::Controller';

sub index_action {
my $self = shift;
return $self->req->param($PLAIN_TEST_KEY) || $self->req->param($UTF_TEST_KEY);
}
1;
}

0 comments on commit 0221962

Please sign in to comment.