Permalink
Browse files

Merge pull request #2 from losomo/master

Decoding utf-8 encoded parameters
  • Loading branch information...
2 parents b3e12c9 + 66d0575 commit 0221962a499de8d05f680b7a4acfcaa2f89aa772 @zby committed Aug 2, 2012
Showing with 72 additions and 0 deletions.
  1. +12 −0 lib/WebNano/Controller.pm
  2. +60 −0 t/utf8.t
View
@@ -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 /;
@@ -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;
}
@@ -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__
View
@@ -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.