Catalyst::Engine::HTTP try select
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / HTTP.pm
1 package Catalyst::Engine::HTTP;
2
3 use strict;
4 use base 'Catalyst::Engine::Test';
5
6 use IO::Socket qw(AF_INET SOCK_STREAM SOMAXCONN);
7
8 =head1 NAME
9
10 Catalyst::Engine::HTTP - Catalyst HTTP Engine
11
12 =head1 SYNOPSIS
13
14 A script using the Catalyst::Engine::HTTP module might look like:
15
16     #!/usr/bin/perl -w
17
18     BEGIN {  $ENV{CATALYST_ENGINE} = 'HTTP' }
19
20     use strict;
21     use lib '/path/to/MyApp/lib';
22     use MyApp;
23
24     MyApp->run;
25
26 =head1 DESCRIPTION
27
28 This is the Catalyst engine specialized for development and testing.
29
30 =head1 OVERLOADED METHODS
31
32 This class overloads some methods from C<Catalyst::Engine::Test>.
33
34 =over 4
35
36 =item $c->run
37
38 =cut
39
40 $SIG{'PIPE'} = 'IGNORE';
41
42 sub run {
43     my $class = shift;
44     my $port  = shift || 3000;
45
46     my $daemon = Catalyst::Engine::HTTP::Catalyst->new(
47         Listen    => SOMAXCONN,
48         LocalPort => $port,
49         ReuseAddr => 1,
50         Timeout   => .1,
51         Type      => SOCK_STREAM,
52     );
53
54     unless ($daemon) {
55         die("Failed to create daemon: $!\n");
56     }
57
58     my $base = URI->new( $daemon->url )->canonical;
59
60     printf( "You can connect to your server at %s\n", $base );
61
62     while ( 1 ) {
63
64         my $connection = $daemon->accept or next;
65
66         while ( my $request = $connection->get_request ) {
67
68             $request->uri->scheme('http');    # Force URI::http
69             $request->uri->host( $base->host );
70             $request->uri->port( $base->port );
71
72             my $lwp = Catalyst::Engine::Test::LWP->new(
73                 request  => $request,
74                 address  => $connection->peerhost,
75                 hostname => gethostbyaddr( $connection->peeraddr, AF_INET )
76             );
77
78             $class->handler($lwp);
79             $connection->send_response( $lwp->response );
80         }
81
82         $connection->close;
83         undef($connection);
84     }
85 }
86
87 =back
88
89 =head1 SEE ALSO
90
91 L<Catalyst>, L<HTTP::Daemon>.
92
93 =head1 AUTHOR
94
95 Sebastian Riedel, C<sri@cpan.org>
96 Christian Hansen, C<ch@ngmedia.com>
97
98 =head1 COPYRIGHT
99
100 This program is free software, you can redistribute it and/or modify it under
101 the same terms as Perl itself.
102
103 =cut
104
105 package Catalyst::Engine::HTTP::Catalyst;
106
107 use strict;
108 use base 'HTTP::Daemon';
109
110 sub product_tokens {
111     "Catalyst/$Catalyst::VERSION";
112 }
113
114 1;