Commit 1838da15 by PotatoGim

mojolicious: take a walk around the official tutorial.

parent 87342e89
#!/usr/bin/env perl
#=============================================================================
# FILE: conditions.pl
# USAGE: ./conditions.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 02시 04분 00초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# agent, host와 같은 조건으로 더 강력한 경로 구성이 가능하다.
# Firefox
get '/foo' => (agent => qw/Firefox/) => sub {
my $c = shift;
$c->render(text => "Congratulations, you are using a cool browser.");
};
# Intenet Explorer
get '/foo' => (agent => qr/Internet Explorer/) => sub {
my $c = shift;
$c->render(text => "Dude, you really need to upgrade to Firefox.");
};
# http://mojolicio.us/bar
get '/bar' => (host => "mojolicio.us") => sub {
my $c = shift;
$c->render(text => "Hello Mojolicious.");
};
app->start;
1;
__END__
=encoding utf8
=head1 NAME
conditions.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
#!/usr/bin/env perl
#=============================================================================
# FILE: content_negotiation.pl
# USAGE: ./content_negotiation.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 01시 29분 56초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# /hello (Accept: application/json)
# /hello (Accept: application/xml)
# /hello.json
# /hello.xml
# /hello?format=json
# /hello?format=xml
get '/hello' => sub {
my $c = shift;
$c->respond_to (
json => { json => { hello => 'world' } },
xml => { text => '<hello>world</hello>' },
any => { data => '', status => 204 }
);
};
# 별다른 설명이 필요 없을 듯...
# 말 그대로 내용 협상이고, 요청에 따라 핸들링되는 데이터가 가변적이라는 특징이
# 있음.
# 다만 요청할 수 있는 형식이 크게 3가지가 있음을 유의하자.
#
# 1. MIME 유형
# 2. 확장자
# 3. format 매개변수
#
# 덧대어, MIME 유형은 아래와 같이 쉽게 변경/확장 가능하다고 한다.
#
# app->types->type(rdf => "application/rdf+xml");
app->start;
1;
__END__
=encoding utf8
=head1 NAME
content_negotiation.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
#!/usr/bin/env perl
#=============================================================================
# FILE: external_templates.pl
# USAGE: ./external_templates.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 01시 44분 40초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# Render template "templates/foo/bar.html.ep"
# 외부 템플릿은 templates 디렉터리에서 검색되며, DATA 섹션보다 우선 순위 높음.
any '/external' => sub {
my $c = shift;
$c->render(template => "foo/bar");
};
app->start;
1;
__END__
=encoding utf8
=head1 NAME
external_templates.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
#!/usr/bin/env perl
#=============================================================================
# FILE: file_uploads.pl
# USAGE: ./file_uploads.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 02시 15분 16초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
# multipart/form-data 요청으로 올려지는 모든 파일들은 자동으로 Mojo::Upload
# 객체로 사용 가능하고, 메모리 점유율은 신경 안써도 된다.
# 왜냐고? 250KiB 이상의 모든 파일들은 자동으로 임시 파일로 스트림되니까!
use Mojolicious::Lite;
# Upload form in DATA section
get '/' => 'form';
# Multipart upload handler
post '/upload' => sub {
my $c = shift;
# Check file size
# 여기서의 제한이 바로 아래에 있는 "$ENV{MOJO_MAX_MESSAGE_SIZE}"다.
return $c->render(text => 'File is too big.', status => 200)
if $c->req->is_limit_exceeded;
# Process uploaded file
return $c->redirect_to('form') unless my $example = $c->param('example');
my $size = $example->size;
my $name = $example->filename;
$c->render(text => "Thanks for uploading $size byte file $name.");
};
# Increase limit to 1GB
$ENV{MOJO_MAX_MESSAGE_SIZE} = 1073741824;
app->start;
# "form_for" 태그 보조자는 Mojolicious::Plugin::TagHelpers를 참고!
# "file_field", "submit_button" 등도 마찬가지...
__DATA__
@@ form.html.ep
<!DOCTYPE html>
<html>
<head><title>Upload</title></head>
<body>
%= form_for upload => (enctype => 'multipart/form-data') => begin
%= file_field 'example'
%= submit_button 'Upload'
% end
</body>
</html>
#!/usr/bin/env perl
#=============================================================================
# FILE: formats.pl
# USAGE: ./formats.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 00시 29분 29초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# /detection
# /detection.html
# /detection.txt
get '/detection' => sub {
my $c = shift;
$c->render(template => 'detected');
};
app->start;
1;
__END__
=encoding utf8
=head1 NAME
formats.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
__DATA__
@@ detected.html.ep
<!DOCTYPE html>
<html>
<head><title>Detected</title></head>
<body>HTML was detected.</body>
</html>
@@ detected.txt.ep
TXT was detected.
#!/usr/bin/env perl
#=============================================================================
# FILE: formats2.pl
# USAGE: ./formats2.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 00시 47분 18초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# /hello.json
# /hello.txt
get '/hello' => [format => [qw/json txt/]] => sub {
my $c = shift;
return $c->render(json => { hello => 'world' })
if $c->stash('format') eq 'json';
$c->render(text => 'hello world');
};
# 기본 포맷이 html인데 반해 제한적 플레이스 홀더를 이용해서 json과 txt만을
# 특정 유형으로 제한하는 예다.
# 그런데... HTTP 요청에서 stash를 설정하려면 대체 어떻게 해야 하지?
app->start;
1;
__END__
=encoding utf8
=head1 NAME
formats2.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
#!/usr/bin/env perl
#=============================================================================
# FILE: formats3.pl
# USAGE: ./formats3.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 00시 47분 18초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# /hello
# format => 0을 통해 포맷 감지 비활성화
get '/hello' => [format => 0] => { text => 'No format detection.' };
# Disable detection and allow the following routes to re-enable it on demand
# 감지는 비활성화, 요청 처리 재활성화를 위한 라우팅들은 활성화.
# 이 이후의 라우팅들은 모두 포맷 감지가 비활성화되는 듯...
under [format => 0];
# /foo
get '/foo' => { text => 'No format detection again.' };
# /bar.txt
# 여기에선 다시 txt에 대한 포맷 감지 활성화.
get '/bar' => [format => 'txt'] => { text => ' Just one format.' };
app->start;
1;
__END__
=encoding utf8
=head1 NAME
formats3.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
#!/usr/bin/env perl
#=============================================================================
# FILE: mode.pl
# USAGE: ./mode.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 03시 27분 07초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use Mojolicious::Lite;
# Prepare mode specific message during startup
my $msg = app->mode eq 'development' ? 'Development!' : 'Something else!';
get '/' => sub {
my $c = shift;
$c->app->log->debug('Rendering mode specific message');
$c->render(text => $msg);
};
app->log->debug('Starting application');
app->start;
# 디버그 메시지들을 편하게 모으기 위해 Mojo의 "log"로부터 Mojo::Log 객체를
# 사용할 수 있고, Mojolicious 운용 모드를 제품 설정으로 나중에 바꾸기만 하면
# 자동으로 비활성화된다.
# Mojolicious의 "mode" 속성으로도 조정 가능.
#
# 기본 운용 모도는 development이며 MOJO_MODE, PLACK_ENV 환경 변수들이나 명령줄
# 옵션으로 바꿀 수 있다.
#
# development 이외의 모드는 로그 수준을 debug에서 info로 변경
#
# 모든 메시지는 STDERR이나 log/$mode.log로 쓰여진다. (log 디렉터리가 존재하면)
#!/usr/bin/env perl
#=============================================================================
# FILE: sessions.pl
# USAGE: ./sessions.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 02시 07분 23초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
# 쿠키 기반의 세션은 "session" 보조자를 통해 사용함과 동시에 작동한다.
#
# 모든 세션 데이터는 Mojo::JSON을 통해 직렬화된다는 점과 클라이언트 측에
# 저장된다는 점을 유의할 것!
#
# 변조 방지를 위해 암호화된 서명과 함께 저장됨.
use Mojolicious::Lite;
# Access session data in action and template
get '/counter' => sub {
my $c = shift;
$c->session->{counter}++;
};
app->start;
# 서명된 쿠키들의 보안을 보장하기 위해서는 별도의 "secrets"를 사용.
# app->secrets(['My secret passphrase here']);
1;
__DATA__
@@ counter.html.ep
Counter: <%= session 'counter' %>
#!/usr/bin/env perl
#=============================================================================
# FILE: static_files.pl
# USAGE: ./static_files.pl
# OPTIONS:
# BRIEF:
# AUTHOR: Ji-Hyeon Gim <potatogim@potatogim.net>
# ORGANIZATION:
# DATE: 2015년 07월 12일 01시 37분 16초
# VERSION: 1.0
# LICENSE: Artistic License 2.0
# NOTE:
#=============================================================================
use strict;
use warnings;
use utf8;
use Mojolicious::Lite;
# 템플릿과 유사하지만 단일 파일 확장자와 Base64 인코딩만 허용된다.
# 정적 파일은 DATA 섹션에 인라인되고 자동적으로 제공된다.
#
# 단, 외부 단일 파일들은 단일 파일 확장자로 제한되지 않는다.
# public 디렉터리가 있다면 여기에서 자동으로 제공.
#
# GET과 HEAD 요청에 대한 라우팅보다 높은 우선 순위를 갖는다.
#
# Range, If-None-Match, If-Modified-Since 헤더와 함께 내용 협상이 지원되며,
# Mojolicious::Command::get으로 쉽게 테스트 가능.
#
# 이는 그 예제
# ./myapp.pl get /something.js -v -H 'Range: bytes=2-4'
app->start;
1;
__END__
=encoding utf8
=head1 NAME
static_files.pl -
=head1 SYNOPSIS
=head1 DESCRIPTION
=over
=item B<Item 1>
=item B<Item 2>
=item B<Item 3>
=back
=head1 AUTHOR
Ji-Hyeon Gim <potatogim@potatogim.net>
=head1 CONTRIBUTORS
=head1 COPYRIGHT AND LICENSE
Copyright(c) 2015 by Ji-Hyeon Gim <potatogim@potatogim.net>
This is free software; you can redistribute it and/or modify it
under the same terms as Perl 5 itself at:
L<http://www.perlfoundation.org/artistic_license_2_0>
You may obtain a copy of the full license at:
L<http://www.perl.com/perl/misc/Artistic.html>
=head1 SEE ALSO
=cut
__DATA__
@@ something.js