File: Controller.pm

package info (click to toggle)
libmojolicious-perl 5.54%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,232 kB
  • ctags: 1,223
  • sloc: perl: 9,581; makefile: 10
file content (1026 lines) | stat: -rw-r--r-- 29,496 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
package Mojolicious::Controller;
use Mojo::Base -base;

# No imports, for security reasons!
use Carp ();
use Mojo::ByteStream;
use Mojo::Transaction::HTTP;
use Mojo::URL;
use Mojo::Util;
use Mojolicious;
use Mojolicious::Routes::Match;
use Scalar::Util ();
use Time::HiRes  ();

has app => sub { Mojolicious->new };
has match =>
  sub { Mojolicious::Routes::Match->new(root => shift->app->routes) };
has tx => sub { Mojo::Transaction::HTTP->new };

# Reserved stash values
my %RESERVED = map { $_ => 1 } (
  qw(action app cb controller data extends format handler json layout),
  qw(namespace path status template text variant)
);

sub AUTOLOAD {
  my $self = shift;

  my ($package, $method) = our $AUTOLOAD =~ /^(.+)::(.+)$/;
  Carp::croak "Undefined subroutine &${package}::$method called"
    unless Scalar::Util::blessed $self && $self->isa(__PACKAGE__);

  # Call helper with current controller
  Carp::croak qq{Can't locate object method "$method" via package "$package"}
    unless my $helper = $self->app->renderer->get_helper($method);
  return $self->$helper(@_);
}

sub continue { $_[0]->app->routes->continue($_[0]) }

sub cookie {
  my ($self, $name) = (shift, shift);

  # Multiple names
  return map { $self->cookie($_) } @$name if ref $name eq 'ARRAY';

  # Response cookie
  if (@_) {

    # Cookie too big
    my $cookie = {name => $name, value => shift, %{shift || {}}};
    $self->app->log->error(qq{Cookie "$name" is bigger than 4096 bytes.})
      if length $cookie->{value} > 4096;

    $self->res->cookies($cookie);
    return $self;
  }

  # Request cookies
  return undef unless my $cookie = $self->req->cookie($name);
  return $cookie->value;
}

sub every_cookie {
  [map { $_->value } @{shift->req->every_cookie(shift)}];
}

sub every_param { _param(@_) }

sub every_signed_cookie { _signed_cookie(@_) }

sub finish {
  my $self = shift;

  # WebSocket
  my $tx = $self->tx;
  $tx->finish(@_) and return $self if $tx->is_websocket;

  # Chunked stream
  return @_ ? $self->write_chunk(@_)->write_chunk('') : $self->write_chunk('')
    if $tx->res->content->is_chunked;

  # Normal stream
  return @_ ? $self->write(@_)->write('') : $self->write('');
}

sub flash {
  my $self = shift;

  # Check old flash
  my $session = $self->session;
  return $session->{flash} ? $session->{flash}{$_[0]} : undef
    if @_ == 1 && !ref $_[0];

  # Initialize new flash and merge values
  my $values = ref $_[0] ? $_[0] : {@_};
  @{$session->{new_flash} ||= {}}{keys %$values} = values %$values;

  return $self;
}

sub helpers { $_[0]->app->renderer->get_helper('')->($_[0]) }

sub on {
  my ($self, $name, $cb) = @_;
  my $tx = $self->tx;
  $self->rendered(101) if $tx->is_websocket;
  return $tx->on($name => sub { shift; $self->$cb(@_) });
}

sub param {
  my ($self, $name) = (shift, shift);

  # Multiple names
  return map { $self->param($_) } @$name if ref $name eq 'ARRAY';

  # List names
  my $captures = $self->stash->{'mojo.captures'} ||= {};
  my $req = $self->req;
  unless (defined $name) {
    my %seen;
    my @keys = grep { !$seen{$_}++ } $req->param;
    push @keys, grep { !$seen{$_}++ } map { $_->name } @{$req->uploads};
    push @keys, grep { !$RESERVED{$_} && !$seen{$_}++ } keys %$captures;
    return sort @keys;
  }

  # Value
  return _param($self, $name)->[-1] unless @_;

  # Override values
  $captures->{$name} = @_ > 1 ? [@_] : $_[0];
  return $self;
}

sub redirect_to {
  my $self = shift;

  # Don't override 3xx status
  my $res = $self->res;
  $res->headers->location($self->url_for(@_));
  return $self->rendered($res->is_status_class(300) ? () : 302);
}

sub render {
  my $self = shift;

  # Template may be first argument
  my ($template, $args) = (@_ % 2 ? shift : undef, {@_});
  $args->{template} = $template if $template;
  my $app     = $self->app;
  my $plugins = $app->plugins->emit_hook(before_render => $self, $args);
  my $maybe   = delete $args->{'mojo.maybe'};

  # Render
  my $ts = $args->{'mojo.to_string'};
  my ($output, $format) = $app->renderer->render($self, $args);
  return defined $output ? Mojo::ByteStream->new($output) : undef if $ts;

  # Maybe
  return $maybe ? undef : !$self->render_not_found unless defined $output;

  # Prepare response
  $plugins->emit_hook(after_render => $self, \$output, $format);
  my $headers = $self->res->body($output)->headers;
  $headers->content_type($app->types->type($format) || 'text/plain')
    unless $headers->content_type;
  return !!$self->rendered($self->stash->{status});
}

sub render_exception { shift->helpers->reply->exception(@_) }

sub render_later { shift->stash('mojo.rendered' => 1) }

sub render_maybe { shift->render(@_, 'mojo.maybe' => 1) }

sub render_not_found { shift->helpers->reply->not_found }

# DEPRECATED in Tiger Face!
sub render_static {
  Mojo::Util::deprecated 'Mojolicious::Controller::render_static is DEPRECATED'
    . ' in favor of the reply->static helper';
  shift->helpers->reply->static(@_);
}

sub render_to_string { shift->render(@_, 'mojo.to_string' => 1) }

sub rendered {
  my ($self, $status) = @_;

  # Disable auto rendering and make sure we have a status
  my $res = $self->render_later->res;
  $res->code($status || 200) if $status || !$res->code;

  # Finish transaction
  my $stash = $self->stash;
  unless ($stash->{'mojo.finished'}++) {

    # Stop timer
    my $app = $self->app;
    if (my $started = delete $stash->{'mojo.started'}) {
      my $elapsed = sprintf '%f',
        Time::HiRes::tv_interval($started, [Time::HiRes::gettimeofday()]);
      my $rps  = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
      my $code = $res->code;
      my $msg  = $res->message || $res->default_message($code);
      $app->log->debug("$code $msg (${elapsed}s, $rps/s).");
    }

    $app->plugins->emit_hook_reverse(after_dispatch => $self);
    $app->sessions->store($self);
  }
  $self->tx->resume;
  return $self;
}

sub req { shift->tx->req }
sub res { shift->tx->res }

sub respond_to {
  my $self = shift;
  my $args = ref $_[0] ? $_[0] : {@_};

  # Find target
  my $target;
  my $renderer = $self->app->renderer;
  my @formats  = @{$renderer->accepts($self)};
  for my $format (@formats ? @formats : ($renderer->default_format)) {
    next unless $target = $args->{$format};
    $self->stash->{format} = $format;
    last;
  }

  # Fallback
  unless ($target) {
    return $self->rendered(204) unless $target = $args->{any};
    delete $self->stash->{format};
  }

  # Dispatch
  ref $target eq 'CODE' ? $target->($self) : $self->render(%$target);

  return $self;
}

sub send {
  my ($self, $msg, $cb) = @_;
  my $tx = $self->tx;
  Carp::croak 'No WebSocket connection to send message to'
    unless $tx->is_websocket;
  $tx->send($msg, $cb ? sub { shift; $self->$cb(@_) } : ());
  return $self->rendered(101);
}

sub session {
  my $self = shift;

  # Hash
  my $session = $self->stash->{'mojo.session'} ||= {};
  return $session unless @_;

  # Get
  return $session->{$_[0]} unless @_ > 1 || ref $_[0];

  # Set
  my $values = ref $_[0] ? $_[0] : {@_};
  @$session{keys %$values} = values %$values;

  return $self;
}

sub signed_cookie {
  my ($self, $name, $value, $options) = @_;

  # Multiple names
  return map { $self->signed_cookie($_) } @$name if ref $name eq 'ARRAY';

  # Request cookie
  return _signed_cookie($self, $name)->[-1] unless defined $value;

  # Response cookie
  my $checksum
    = Mojo::Util::hmac_sha1_sum($value, $self->stash->{'mojo.secrets'}[0]);
  return $self->cookie($name, "$value--$checksum", $options);
}

sub stash { Mojo::Util::_stash(stash => @_) }

sub url_for {
  my $self = shift;
  my $target = shift // '';

  # Absolute URL
  return $target if Scalar::Util::blessed $target && $target->isa('Mojo::URL');
  return Mojo::URL->new($target) if $target =~ m!^(?:[^:/?#]+:|//)!;

  # Base
  my $url  = Mojo::URL->new;
  my $req  = $self->req;
  my $base = $url->base($req->url->base->clone)->base->userinfo(undef);

  # Relative URL
  my $path = $url->path;
  if ($target =~ m!^/!) {
    if (my $prefix = $self->stash->{path}) {
      my $real = $req->url->path->to_route;
      $real =~ s!/?\Q$prefix\E$!$target!;
      $target = $real;
    }
    $url->parse($target);
  }

  # Route
  else {
    my $generated = $self->match->path_for($target, @_);
    $path->parse($generated->{path}) if $generated->{path};
    $base->scheme($base->protocol eq 'https' ? 'wss' : 'ws')
      if $generated->{websocket};
  }

  # Make path absolute
  my $base_path = $base->path;
  unshift @{$path->parts}, @{$base_path->parts};
  $base_path->parts([])->trailing_slash(0);

  return $url;
}

sub validation {
  my $self = shift;

  my $stash = $self->stash;
  return $stash->{'mojo.validation'} if $stash->{'mojo.validation'};

  my $req    = $self->req;
  my $token  = $self->session->{csrf_token};
  my $header = $req->headers->header('X-CSRF-Token');
  my $hash   = $req->params->to_hash;
  $hash->{csrf_token} //= $header if $token && $header;
  my $validation = $self->app->validator->validation->input($hash);
  return $stash->{'mojo.validation'} = $validation->csrf_token($token);
}

sub write {
  my ($self, $chunk, $cb) = @_;
  ($cb, $chunk) = ($chunk, undef) if ref $chunk eq 'CODE';
  $self->res->content->write($chunk, $cb ? sub { shift; $self->$cb(@_) } : ());
  return $self->rendered;
}

sub write_chunk {
  my ($self, $chunk, $cb) = @_;
  ($cb, $chunk) = ($chunk, undef) if ref $chunk eq 'CODE';
  my $content = $self->res->content;
  $content->write_chunk($chunk, $cb ? sub { shift; $self->$cb(@_) } : ());
  return $self->rendered;
}

sub _param {
  my ($self, $name) = @_;

  # Captured unreserved values
  my $captures = $self->stash->{'mojo.captures'} ||= {};
  if (!$RESERVED{$name} && defined(my $value = $captures->{$name})) {
    return ref $value eq 'ARRAY' ? $value : [$value];
  }

  # Uploads or param values
  my $req     = $self->req;
  my $uploads = $req->every_upload($name);
  return @$uploads ? $uploads : $req->every_param($name);
}

sub _signed_cookie {
  my ($self, $name) = @_;

  my $secrets = $self->stash->{'mojo.secrets'};
  my @results;
  for my $value (@{$self->every_cookie($name)}) {

    # Check signature with rotating secrets
    if ($value =~ s/--([^\-]+)$//) {
      my $signature = $1;

      my $valid;
      for my $secret (@$secrets) {
        my $check = Mojo::Util::hmac_sha1_sum($value, $secret);
        ++$valid and last if Mojo::Util::secure_compare($signature, $check);
      }
      if ($valid) { push @results, $value }

      else { $self->app->log->debug(qq{Cookie "$name" has bad signature.}) }
    }

    else { $self->app->log->debug(qq{Cookie "$name" not signed.}) }
  }

  return \@results;
}

1;

=encoding utf8

=head1 NAME

Mojolicious::Controller - Controller base class

=head1 SYNOPSIS

  # Controller
  package MyApp::Controller::Foo;
  use Mojo::Base 'Mojolicious::Controller';

  # Action
  sub bar {
    my $self = shift;
    my $name = $self->param('name');
    $self->res->headers->cache_control('max-age=1, no-cache');
    $self->render(json => {hello => $name});
  }

=head1 DESCRIPTION

L<Mojolicious::Controller> is the base class for your L<Mojolicious>
controllers. It is also the default controller class unless you set
L<Mojolicious/"controller_class">.

=head1 ATTRIBUTES

L<Mojolicious::Controller> inherits all attributes from L<Mojo::Base> and
implements the following new ones.

=head2 app

  my $app = $c->app;
  $c      = $c->app(Mojolicious->new);

A reference back to the application that dispatched to this controller,
defaults to a L<Mojolicious> object.

  # Use application logger
  $c->app->log->debug('Hello Mojo!');

  # Generate path
  my $path = $c->app->home->rel_file('templates/foo/bar.html.ep');

=head2 match

  my $m = $c->match;
  $c    = $c->match(Mojolicious::Routes::Match->new);

Router results for the current request, defaults to a
L<Mojolicious::Routes::Match> object.

  # Introspect
  my $controller = $c->match->endpoint->pattern->defaults->{controller};
  my $action     = $c->match->stack->[-1]{action};

=head2 tx

  my $tx = $c->tx;
  $c     = $c->tx(Mojo::Transaction::HTTP->new);

The transaction that is currently being processed, usually a
L<Mojo::Transaction::HTTP> or L<Mojo::Transaction::WebSocket> object. Note
that this reference is usually weakened, so the object needs to be referenced
elsewhere as well when you're performing non-blocking operations and the
underlying connection might get closed early.

  # Check peer information
  my $address = $c->tx->remote_address;
  my $port    = $c->tx->remote_port;

  # Perform non-blocking operation without knowing the connection status
  my $tx = $c->tx;
  Mojo::IOLoop->timer(2 => sub {
    $c->app->log->debug($tx->is_finished ? 'Finished.' : 'In progress.');
  });

=head1 METHODS

L<Mojolicious::Controller> inherits all methods from L<Mojo::Base> and
implements the following new ones.

=head2 continue

  $c->continue;

Continue dispatch chain with L<Mojolicious::Routes/"continue">.

=head2 cookie

  my $value       = $c->cookie('foo');
  my ($foo, $bar) = $c->cookie(['foo', 'bar']);
  $c              = $c->cookie(foo => 'bar');
  $c              = $c->cookie(foo => 'bar', {path => '/'});

Access request cookie values and create new response cookies. If there are
multiple values sharing the same name, and you want to access more than just
the last one, you can use L</"every_cookie">.

  # Create response cookie with domain and expiration date
  $c->cookie(user => 'sri', {domain => 'example.com', expires => time + 60});

=head2 every_cookie

  my $values = $c->every_cookie('foo');

Similar to L</"cookie">, but returns all request cookie values sharing the
same name as an array reference.

  $ Get first cookie value
  my $first = $c->every_cookie('foo')->[0];

=head2 every_param

  my $values = $c->every_param('foo');

Similar to L</"param">, but returns all values sharing the same name as an
array reference.

  # Get first value
  my $first = $c->every_param('foo')->[0];

=head2 every_signed_cookie

  my $values = $c->every_signed_cookie('foo');

Similar to L</"signed_cookie">, but returns all signed request cookie values
sharing the same name as an array reference.

  # Get first signed cookie value
  my $first = $c->every_signed_cookie('foo')->[0];

=head2 finish

  $c = $c->finish;
  $c = $c->finish(1000);
  $c = $c->finish(1003 => 'Cannot accept data!');
  $c = $c->finish('Bye!');

Close WebSocket connection or long poll stream gracefully.

=head2 flash

  my $foo = $c->flash('foo');
  $c      = $c->flash({foo => 'bar'});
  $c      = $c->flash(foo => 'bar');

Data storage persistent only for the next request, stored in the
L</"session">.

  # Show message after redirect
  $c->flash(message => 'User created successfully!');
  $c->redirect_to('show_user', id => 23);

=head2 helpers

  my $helpers = $c->helpers;

Return a proxy object containing the current controller object and on which
helpers provided by L</"app"> can be called. This includes all helpers from
L<Mojolicious::Plugin::DefaultHelpers> and L<Mojolicious::Plugin::TagHelpers>.

  # Make sure to use the "title" helper and not the controller method
  $c->helpers->title('Welcome!');

=head2 on

  my $cb = $c->on(finish => sub {...});

Subscribe to events of L</"tx">, which is usually a L<Mojo::Transaction::HTTP>
or L<Mojo::Transaction::WebSocket> object. Note that this method will
automatically respond to WebSocket handshake requests with a C<101> response
status.

  # Do something after the transaction has been finished
  $c->on(finish => sub {
    my $c = shift;
    $c->app->log->debug('We are done!');
  });

  # Receive WebSocket message
  $c->on(message => sub {
    my ($c, $msg) = @_;
    $c->app->log->debug("Message: $msg");
  });

  # Receive JSON object via WebSocket message
  $c->on(json => sub {
    my ($c, $hash) = @_;
    $c->app->log->debug("Test: $hash->{test}");
  });

  # Receive WebSocket "Binary" message
  $c->on(binary => sub {
    my ($c, $bytes) = @_;
    my $len = length $bytes;
    $c->app->log->debug("Received $len bytes.");
  });

=head2 param

  my @names       = $c->param;
  my $value       = $c->param('foo');
  my ($foo, $bar) = $c->param(['foo', 'bar']);
  $c              = $c->param(foo => 'ba;r');
  $c              = $c->param(foo => qw(ba;r baz));
  $c              = $c->param(foo => ['ba;r', 'baz']);

Access route placeholder values that are not reserved stash values, file
uploads as well as C<GET> and C<POST> parameters extracted from the query
string and C<application/x-www-form-urlencoded> or C<multipart/form-data>
message body, in that order. If there are multiple values sharing the same
name, and you want to access more than just the last one, you can use
L</"every_param">. Parts of the request body need to be loaded into memory to
parse C<POST> parameters, so you have to make sure it is not excessively
large, there's a 10MB limit by default.

  # Get first value
  my $first = $c->every_param('foo')->[0];

For more control you can also access request information directly.

  # Only GET parameters
  my $foo = $c->req->url->query->param('foo');

  # Only POST parameters
  my $foo = $c->req->body_params->param('foo');

  # Only GET and POST parameters
  my $foo = $c->req->param('foo');

  # Only file uploads
  my $foo = $c->req->upload('foo');

=head2 redirect_to

  $c = $c->redirect_to('named', foo => 'bar');
  $c = $c->redirect_to('named', {foo => 'bar'});
  $c = $c->redirect_to('/perldoc');
  $c = $c->redirect_to('http://mojolicio.us/perldoc');

Prepare a C<302> redirect response, takes the same arguments as L</"url_for">.

  # Moved permanently
  $c->res->code(301);
  $c->redirect_to('some_route');

=head2 render

  my $bool = $c->render;
  my $bool = $c->render(controller => 'foo', action => 'bar');
  my $bool = $c->render(template => 'foo/index');
  my $bool = $c->render(template => 'index', format => 'html');
  my $bool = $c->render(data => $bytes);
  my $bool = $c->render(text => 'Hello!');
  my $bool = $c->render(json => {foo => 'bar'});
  my $bool = $c->render(handler => 'something');
  my $bool = $c->render('foo/index');

Render content with L<Mojolicious::Renderer/"render"> and emit hooks
L<Mojolicious/"before_render"> as well as L<Mojolicious/"after_render">. If no
template is provided a default one based on controller and action or route
name will be generated with L<Mojolicious::Renderer/"template_for">, all
additional pairs get merged into the L</"stash">.

  # Render characters
  $c->render(text => 'I ♥ Mojolicious!');

  # Render binary data
  use Mojo::JSON 'encode_json';
  $c->render(data => encode_json({test => 'I ♥ Mojolicious!'}));

  # Render JSON
  $c->render(json => {test => 'I ♥ Mojolicious!'});

  # Render template "foo/bar.html.ep"
  $c->render(template => 'foo/bar', format => 'html', handler => 'ep');

  # Render template "foo/bar.*.*"
  $c->render(template => 'foo/bar');

  # Render template "test.xml.*"
  $c->render('test', format => 'xml');

=head2 render_exception

  $c = $c->render_exception('Oops!');
  $c = $c->render_exception(Mojo::Exception->new('Oops!'));

Alias for L<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>exception">.

=head2 render_later

  $c = $c->render_later;

Disable automatic rendering to delay response generation, only necessary if
automatic rendering would result in a response.

  # Delayed rendering
  $c->render_later;
  Mojo::IOLoop->timer(2 => sub {
    $c->render(text => 'Delayed by 2 seconds!');
  });

=head2 render_maybe

  my $bool = $c->render_maybe;
  my $bool = $c->render_maybe(controller => 'foo', action => 'bar');
  my $bool = $c->render_maybe('foo/index', format => 'html');

Try to render content, but do not call
L<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>not_found"> if no response
could be generated, takes the same arguments as L</"render">.

  # Render template "index_local" only if it exists
  $c->render_maybe('index_local') or $c->render('index');

=head2 render_not_found

  $c = $c->render_not_found;

Alias for L<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>not_found">.

=head2 render_to_string

  my $output = $c->render_to_string('foo/index', format => 'pdf');

Try to render content and return it wrapped in a L<Mojo::ByteStream> object or
return C<undef>, all arguments get localized automatically and are only
available during this render operation, takes the same arguments as
L</"render">.

=head2 rendered

  $c = $c->rendered;
  $c = $c->rendered(302);

Finalize response and emit hook L<Mojolicious/"after_dispatch">, defaults to
using a C<200> response code.

  # Custom response
  $c->res->headers->content_type('text/plain');
  $c->res->body('Hello World!');
  $c->rendered(200);

  # Accept WebSocket handshake without subscribing to an event
  $c->rendered(101);

=head2 req

  my $req = $c->req;

Get L<Mojo::Message::Request> object from L</"tx">.

  # Longer version
  my $req = $c->tx->req;

  # Extract request information
  my $url   = $c->req->url->to_abs;
  my $info  = $c->req->url->to_abs->userinfo;
  my $host  = $c->req->url->to_abs->host;
  my $agent = $c->req->headers->user_agent;
  my $bytes = $c->req->body;
  my $str   = $c->req->text;
  my $hash  = $c->req->params->to_hash;
  my $value = $c->req->json;
  my $foo   = $c->req->json('/23/foo');
  my $dom   = $c->req->dom;
  my $bar   = $c->req->dom('div.bar')->first->text;

=head2 res

  my $res = $c->res;

Get L<Mojo::Message::Response> object from L</"tx">.

  # Longer version
  my $res = $c->tx->res;

  # Force file download by setting a custom response header
  $c->res->headers->content_disposition('attachment; filename=foo.png;');

=head2 respond_to

  $c = $c->respond_to(
    json => {json => {message => 'Welcome!'}},
    html => {template => 'welcome'},
    any  => sub {...}
  );

Automatically select best possible representation for resource from C<Accept>
request header, C<format> stash value or C<format> C<GET>/C<POST> parameter,
defaults to rendering an empty C<204> response. Since browsers often don't
really know what they actually want, unspecific C<Accept> request headers with
more than one MIME type will be ignored, unless the C<X-Requested-With> header
is set to the value C<XMLHttpRequest>.

  $c->respond_to(
    json => sub { $c->render(json => {just => 'works'}) },
    xml  => {text => '<just>works</just>'},
    any  => {data => '', status => 204}
  );

For more advanced negotiation logic you can also use the helper
L<Mojolicious::Plugin::DefaultHelpers/"accepts">.

=head2 send

  $c = $c->send({binary => $bytes});
  $c = $c->send({text   => $bytes});
  $c = $c->send({json   => {test => [1, 2, 3]}});
  $c = $c->send([$fin, $rsv1, $rsv2, $rsv3, $op, $payload]);
  $c = $c->send($chars);
  $c = $c->send($chars => sub {...});

Send message or frame non-blocking via WebSocket, the optional drain callback
will be invoked once all data has been written. Note that this method will
automatically respond to WebSocket handshake requests with a C<101> response
status.

  # Send "Text" message
  $c->send('I ♥ Mojolicious!');

  # Send JSON object as "Text" message
  $c->send({json => {test => 'I ♥ Mojolicious!'}});

  # Send JSON object as "Binary" message
  use Mojo::JSON 'encode_json';
  $c->send({binary => encode_json({test => 'I ♥ Mojolicious!'})});

  # Send "Ping" frame
  $c->send([1, 0, 0, 0, 9, 'Hello World!']);

  # Make sure previous message has been written before continuing
  $c->send('First message!' => sub {
    my $c = shift;
    $c->send('Second message!');
  });

For mostly idle WebSockets you might also want to increase the inactivity
timeout with L<Mojolicious::Plugin::DefaultHelpers/"inactivity_timeout">,
which usually defaults to C<15> seconds.

  # Increase inactivity timeout for connection to 300 seconds
  $c->inactivity_timeout(300);

=head2 session

  my $session = $c->session;
  my $foo     = $c->session('foo');
  $c          = $c->session({foo => 'bar'});
  $c          = $c->session(foo => 'bar');

Persistent data storage for the next few requests, all session data gets
serialized with L<Mojo::JSON> and stored Base64 encoded in HMAC-SHA1 signed
cookies. Note that cookies usually have a C<4096> byte (4KB) limit, depending
on browser.

  # Manipulate session
  $c->session->{foo} = 'bar';
  my $foo = $c->session->{foo};
  delete $c->session->{foo};

  # Expiration date in seconds from now (persists between requests)
  $c->session(expiration => 604800);

  # Expiration date as absolute epoch time (only valid for one request)
  $c->session(expires => time + 604800);

  # Delete whole session by setting an expiration date in the past
  $c->session(expires => 1);

=head2 signed_cookie

  my $value       = $c->signed_cookie('foo');
  my ($foo, $bar) = $c->signed_cookie(['foo', 'bar']);
  $c              = $c->signed_cookie(foo => 'bar');
  $c              = $c->signed_cookie(foo => 'bar', {path => '/'});

Access signed request cookie values and create new signed response cookies. If
there are multiple values sharing the same name, and you want to access more
than just the last one, you can use L</"every_signed_cookie">. Cookies failing
HMAC-SHA1 signature verification will be automatically discarded.

=head2 stash

  my $hash = $c->stash;
  my $foo  = $c->stash('foo');
  $c       = $c->stash({foo => 'bar'});
  $c       = $c->stash(foo => 'bar');

Non-persistent data storage and exchange for the current request, application
wide default values can be set with L<Mojolicious/"defaults">. Some stash
values have a special meaning and are reserved, the full list is currently
C<action>, C<app>, C<cb>, C<controller>, C<data>, C<extends>, C<format>,
C<handler>, C<json>, C<layout>, C<namespace>, C<path>, C<status>, C<template>,
C<text> and C<variant>. Note that all stash values with a C<mojo.*> prefix are
reserved for internal use.

  # Remove value
  my $foo = delete $c->stash->{foo};

=head2 url_for

  my $url = $c->url_for;
  my $url = $c->url_for(name => 'sebastian');
  my $url = $c->url_for({name => 'sebastian'});
  my $url = $c->url_for('test', name => 'sebastian');
  my $url = $c->url_for('test', {name => 'sebastian'});
  my $url = $c->url_for('/perldoc');
  my $url = $c->url_for('//mojolicio.us/perldoc');
  my $url = $c->url_for('http://mojolicio.us/perldoc');
  my $url = $c->url_for('mailto:sri@example.com');

Generate a portable L<Mojo::URL> object with base for a path, URL or route.

  # "http://127.0.0.1:3000/perldoc" if application has been started with Morbo
  $c->url_for('/perldoc')->to_abs;

  # "/perldoc?foo=bar" if application is deployed under "/"
  $c->url_for('/perldoc')->query(foo => 'bar');

  # "/myapp/perldoc?foo=bar" if application is deployed under "/myapp"
  $c->url_for('/perldoc')->query(foo => 'bar');

You can also use the helper L<Mojolicious::Plugin::DefaultHelpers/"url_with">
to inherit query parameters from the current request.

  # "/list?q=mojo&page=2" if current request was for "/list?q=mojo&page=1"
  $c->url_with->query([page => 2]);

=head2 validation

  my $validation = $c->validation;

Get L<Mojolicious::Validator::Validation> object for current request to
validate C<GET> and C<POST> parameters extracted from the query string and
C<application/x-www-form-urlencoded> or C<multipart/form-data> message body.
Parts of the request body need to be loaded into memory to parse C<POST>
parameters, so you have to make sure it is not excessively large, there's a
10MB limit by default.

  my $validation = $c->validation;
  $validation->required('title')->size(3, 50);
  my $title = $validation->param('title');

=head2 write

  $c = $c->write;
  $c = $c->write($bytes);
  $c = $c->write(sub {...});
  $c = $c->write($bytes => sub {...});

Write dynamic content non-blocking, the optional drain callback will be
invoked once all data has been written.

  # Keep connection alive (with Content-Length header)
  $c->res->headers->content_length(6);
  $c->write('Hel' => sub {
    my $c = shift;
    $c->write('lo!')
  });

  # Close connection when finished (without Content-Length header)
  $c->write('Hel' => sub {
    my $c = shift;
    $c->write('lo!' => sub {
      my $c = shift;
      $c->finish;
    });
  });

For Comet (long polling) you might also want to increase the inactivity
timeout with L<Mojolicious::Plugin::DefaultHelpers/"inactivity_timeout">,
which usually defaults to C<15> seconds.

  # Increase inactivity timeout for connection to 300 seconds
  $c->inactivity_timeout(300);

=head2 write_chunk

  $c = $c->write_chunk;
  $c = $c->write_chunk($bytes);
  $c = $c->write_chunk(sub {...});
  $c = $c->write_chunk($bytes => sub {...});

Write dynamic content non-blocking with C<chunked> transfer encoding, the
optional drain callback will be invoked once all data has been written.

  # Make sure previous chunk has been written before continuing
  $c->write_chunk('He' => sub {
    my $c = shift;
    $c->write_chunk('ll' => sub {
      my $c = shift;
      $c->finish('o!');
    });
  });

You can call L</"finish"> at any time to end the stream.

  2
  He
  2
  ll
  2
  o!
  0

=head1 AUTOLOAD

In addition to the L</"ATTRIBUTES"> and L</"METHODS"> above you can also call
helpers provided by L</"app"> on L<Mojolicious::Controller> objects. This
includes all helpers from L<Mojolicious::Plugin::DefaultHelpers> and
L<Mojolicious::Plugin::TagHelpers>.

  $c->layout('green');
  $c->title('Welcome!');

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.

=cut