Commit | Line | Data |
5c33dda5 |
1 | package Web::Simple::Application; |
2 | |
975048a1 |
3 | use Scalar::Util 'weaken'; |
7346dbd3 |
4 | use Try::Tiny; |
975048a1 |
5 | |
8bd060f4 |
6 | use Moo; |
5c33dda5 |
7 | |
876e62e1 |
8 | has 'config' => ( |
9 | is => 'ro', |
10 | default => sub { |
11 | my ($self) = @_; |
12 | +{ $self->default_config } |
13 | }, |
14 | trigger => sub { |
15 | my ($self, $value) = @_; |
16 | my %default = $self->default_config; |
17 | my @not = grep !exists $value->{$_}, keys %default; |
18 | @{$value}{@not} = @default{@not}; |
19 | } |
20 | ); |
5c33dda5 |
21 | |
445b3ea0 |
22 | sub default_config { () } |
39119082 |
23 | |
445b3ea0 |
24 | has '_dispatcher' => (is => 'lazy'); |
5c33dda5 |
25 | |
445b3ea0 |
26 | sub _build__dispatcher { |
27 | my $self = shift; |
28 | require Web::Dispatch; |
445b3ea0 |
29 | my $final = $self->_build_final_dispatcher; |
b5b4423b |
30 | |
31 | # We need to weaken both the copy of $self that the |
32 | # app parameter will close over and the copy that'll |
33 | # be passed through as a node argument. |
34 | # |
35 | # To ensure that this doesn't then result in us being |
36 | # DESTROYed unexpectedly early, our to_psgi_app method |
37 | # closes back over $self |
38 | |
39 | weaken($self); |
1f8cad5e |
40 | my %dispatch_args = ( |
e5250d96 |
41 | dispatch_app => sub { $self->dispatch_request(@_), $final }, |
1f8cad5e |
42 | dispatch_object => $self |
445b3ea0 |
43 | ); |
1f8cad5e |
44 | weaken($dispatch_args{dispatch_object}); |
45 | Web::Dispatch->new(%dispatch_args); |
5c33dda5 |
46 | } |
47 | |
3583ca04 |
48 | sub _build_final_dispatcher { |
4ed4fb42 |
49 | [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ] |
5c33dda5 |
50 | } |
51 | |
5c33dda5 |
52 | sub run_if_script { |
7346dbd3 |
53 | my ( $self ) = @_; |
b9e047ef |
54 | # ->to_psgi_app is true for require() but also works for plackup |
7346dbd3 |
55 | return $self->to_psgi_app if caller(1); |
56 | $self = ref($self) ? $self : $self->_build_for_run_if_script; |
5c33dda5 |
57 | $self->run(@_); |
58 | } |
59 | |
7346dbd3 |
60 | sub _build_for_run_if_script { |
61 | my ( $self ) = @_; |
62 | try { $self->new } |
63 | catch { |
64 | die "Failed to create new '$self' object during run_if_script" |
65 | . " (should your .pm file end with just '1;'?) : $_\n"; |
66 | }; |
67 | } |
68 | |
913a9cf9 |
69 | sub _run_cgi { |
5c33dda5 |
70 | my $self = shift; |
2bc99ccd |
71 | require Plack::Handler::CGI; |
72 | Plack::Handler::CGI->new->run($self->to_psgi_app); |
d3a61609 |
73 | } |
74 | |
e27ab5c5 |
75 | sub _run_fcgi { |
76 | my $self = shift; |
2bc99ccd |
77 | require Plack::Handler::FCGI; |
78 | Plack::Handler::FCGI->new->run($self->to_psgi_app); |
e27ab5c5 |
79 | } |
80 | |
445b3ea0 |
81 | sub to_psgi_app { |
bc57805c |
82 | my $self = ref($_[0]) ? $_[0] : $_[0]->new; |
b5b4423b |
83 | my $app = $self->_dispatcher->to_app; |
84 | |
85 | # Close over $self to keep $self alive even though |
86 | # we weakened the copies the dispatcher has; the |
87 | # if 0 causes the ops to be optimised away to |
88 | # minimise the performance impact and avoid void |
89 | # context warnings while still doing the closing |
90 | # over part. As Mithaldu said: "Gnarly." ... |
91 | |
92 | return sub { $self if 0; goto &$app; }; |
5c33dda5 |
93 | } |
94 | |
913a9cf9 |
95 | sub run { |
96 | my $self = shift; |
66350cd3 |
97 | if ( |
98 | $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH} |
7b930ebb |
99 | || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} ) |
100 | # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid |
66350cd3 |
101 | ) { |
e27ab5c5 |
102 | return $self->_run_fcgi; |
103 | } elsif ($ENV{GATEWAY_INTERFACE}) { |
2514ad17 |
104 | return $self->_run_cgi; |
913a9cf9 |
105 | } |
5b8f03a7 |
106 | unless (@ARGV && $ARGV[0] =~ m{(^[A-Z/])|\@}) { |
db2899c3 |
107 | return $self->_run_cli(@ARGV); |
d104fb1d |
108 | } |
109 | |
4ba6d891 |
110 | my @args = @ARGV; |
913a9cf9 |
111 | |
5b8f03a7 |
112 | unshift(@args, 'GET') if $args[0] !~ /^[A-Z]/; |
4ba6d891 |
113 | |
c1db3355 |
114 | $self->_run_cli_test_request(@args); |
4ba6d891 |
115 | } |
116 | |
c1db3355 |
117 | sub _test_request_spec_to_http_request { |
4ba6d891 |
118 | my ($self, $method, $path, @rest) = @_; |
119 | |
c1db3355 |
120 | # if it's a reference, assume a request object |
121 | return $method if ref($method); |
913a9cf9 |
122 | |
8c3623e2 |
123 | if ($path =~ s/^(.*?)\@//) { |
124 | my $basic = $1; |
125 | require MIME::Base64; |
126 | unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic); |
127 | } |
128 | |
4ba6d891 |
129 | my $request = HTTP::Request->new($method => $path); |
c1db3355 |
130 | |
82bc2f9c |
131 | my @params; |
132 | |
133 | while (my ($header, $value) = splice(@rest, 0, 2)) { |
134 | unless ($header =~ s/:$//) { |
135 | push @params, $header, $value; |
136 | } |
15928515 |
137 | $header =~ s/_/-/g; |
138 | if ($header eq 'Content') { |
139 | $request->content($value); |
140 | } else { |
141 | $request->headers->push_header($header, $value); |
142 | } |
82bc2f9c |
143 | } |
144 | |
9f3d2dd9 |
145 | if (($method eq 'POST' or $method eq 'PUT') and @params) { |
4ba6d891 |
146 | my $content = do { |
147 | require URI; |
148 | my $url = URI->new('http:'); |
9f3d2dd9 |
149 | $url->query_form(@params); |
4ba6d891 |
150 | $url->query; |
151 | }; |
152 | $request->header('Content-Type' => 'application/x-www-form-urlencoded'); |
153 | $request->header('Content-Length' => length($content)); |
154 | $request->content($content); |
155 | } |
c1db3355 |
156 | |
157 | return $request; |
158 | } |
159 | |
160 | sub run_test_request { |
161 | my ($self, @req) = @_; |
162 | |
5b8f03a7 |
163 | require HTTP::Request; |
164 | |
c1db3355 |
165 | require Plack::Test; |
166 | |
167 | my $request = $self->_test_request_spec_to_http_request(@req); |
168 | |
4ba6d891 |
169 | Plack::Test::test_psgi( |
c1db3355 |
170 | $self->to_psgi_app, sub { shift->($request) } |
4ba6d891 |
171 | ); |
c1db3355 |
172 | } |
173 | |
174 | sub _run_cli_test_request { |
175 | my ($self, @req) = @_; |
176 | my $response = $self->run_test_request(@req); |
177 | |
178 | binmode(STDOUT); binmode(STDERR); # for win32 |
179 | |
baabba33 |
180 | print STDERR $response->status_line."\n"; |
181 | print STDERR $response->headers_as_string("\n")."\n"; |
f9d0d382 |
182 | my $content = $response->content; |
183 | $content .= "\n" if length($content) and $content !~ /\n\z/; |
184 | print STDOUT $content if $content; |
913a9cf9 |
185 | } |
186 | |
d104fb1d |
187 | sub _run_cli { |
188 | my $self = shift; |
189 | die $self->_cli_usage; |
190 | } |
191 | |
192 | sub _cli_usage { |
193 | "To run this script in CGI test mode, pass a URL path beginning with /:\n". |
194 | "\n". |
195 | " $0 /some/path\n". |
196 | " $0 /\n" |
197 | } |
198 | |
5c33dda5 |
199 | 1; |
32d29dcd |
200 | |
201 | =head1 NAME |
202 | |
6a4808bf |
203 | Web::Simple::Application - A base class for your Web-Simple application |
32d29dcd |
204 | |
205 | =head1 DESCRIPTION |
206 | |
207 | This is a base class for your L<Web::Simple> application. You probably don't |
208 | need to construct this class yourself, since L<Web::Simple> does the 'heavy |
209 | lifting' for you in that regards. |
210 | |
211 | =head1 METHODS |
212 | |
6a4808bf |
213 | This class exposes the following public methods. |
32d29dcd |
214 | |
215 | =head2 default_config |
216 | |
6a4808bf |
217 | Merges with the C<config> initializer to provide configuration information for |
218 | your application. For example: |
32d29dcd |
219 | |
220 | sub default_config { |
221 | ( |
222 | title => 'Bloggery', |
223 | posts_dir => $FindBin::Bin.'/posts', |
224 | ); |
225 | } |
226 | |
6a4808bf |
227 | Now, the C<config> attribute of C<$self> will be set to a HashRef |
32d29dcd |
228 | containing keys 'title' and 'posts_dir'. |
229 | |
12b3e9a3 |
230 | The keys from default_config are merged into any config supplied, so |
231 | if you construct your application like: |
6a4808bf |
232 | |
12b3e9a3 |
233 | MyWebSimpleApp::Web->new( |
234 | config => { title => 'Spoon', environment => 'dev' } |
235 | ) |
6a4808bf |
236 | |
12b3e9a3 |
237 | then C<config> will contain: |
6a4808bf |
238 | |
12b3e9a3 |
239 | { |
240 | title => 'Spoon', |
241 | posts_dir => '/path/to/myapp/posts', |
242 | environment => 'dev' |
243 | } |
32d29dcd |
244 | |
12b3e9a3 |
245 | =head2 run_if_script |
32d29dcd |
246 | |
12b3e9a3 |
247 | The run_if_script method is designed to be used at the end of the script |
248 | or .pm file where your application class is defined - for example: |
32d29dcd |
249 | |
250 | ## my_web_simple_app.pl |
251 | #!/usr/bin/env perl |
252 | use Web::Simple 'HelloWorld'; |
253 | |
254 | { |
255 | package HelloWorld; |
256 | |
257 | sub dispatch_request { |
258 | sub (GET) { |
259 | [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ] |
260 | }, |
261 | sub () { |
262 | [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ] |
263 | } |
264 | } |
265 | } |
266 | |
267 | HelloWorld->run_if_script; |
268 | |
12b3e9a3 |
269 | This returns a true value, so your file is now valid as a module - so |
6a4808bf |
270 | |
12b3e9a3 |
271 | require 'my_web_simple_app.pl'; |
6a4808bf |
272 | |
12b3e9a3 |
273 | my $hw = HelloWorld->new; |
6a4808bf |
274 | |
12b3e9a3 |
275 | will work fine (and you can rename it to lib/HelloWorld.pm later to make it |
276 | a real use-able module). |
6a4808bf |
277 | |
12b3e9a3 |
278 | However, it detects if it's being run as a script (via testing $0) and if |
279 | so attempts to do the right thing. |
32d29dcd |
280 | |
12b3e9a3 |
281 | If run under a CGI environment, your application will execute as a CGI. |
32d29dcd |
282 | |
12b3e9a3 |
283 | If run under a FastCGI environment, your application will execute as a |
284 | FastCGI process (this works both for dynamic shared-hosting-style FastCGI |
285 | and for apache FastCgiServer style setups). |
32d29dcd |
286 | |
12b3e9a3 |
287 | If run from the commandline with a URL path, it runs a GET request against |
288 | that path - |
32d29dcd |
289 | |
12b3e9a3 |
290 | $ perl -Ilib examples/hello-world/hello-world.cgi / |
291 | 200 OK |
292 | Content-Type: text/plain |
293 | |
294 | Hello world! |
32d29dcd |
295 | |
15928515 |
296 | You can also provide a method name - |
297 | |
298 | $ perl -Ilib examples/hello-world/hello-world.cgi POST / |
299 | 405 Method Not Allowed |
300 | Content-Type: text/plain |
301 | |
302 | Method not allowed |
303 | |
304 | For a POST or PUT request, pairs on the command line will be treated |
305 | as form variables. For any request, pairs on the command line ending in : |
306 | are treated as headers, and 'Content:' will set the request body - |
307 | |
308 | $ ./myapp POST / Accept: text/html form_field_name form_field_value |
309 | |
310 | $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }' |
311 | |
312 | The body of the response is sent to STDOUT and the headers to STDERR, so |
313 | |
314 | $ ./myapp GET / >index.html |
315 | |
316 | will generally do the right thing. |
317 | |
8c3623e2 |
318 | To send basic authentication credentials, use user:pass@ syntax - |
319 | |
320 | $ ./myapp GET bob:secret@/protected/path |
321 | |
12b3e9a3 |
322 | Additionally, you can treat the file as though it were a standard PSGI |
323 | application file (*.psgi). For example you can start up up with C<plackup> |
324 | |
325 | plackup my_web_simple_app.pl |
32d29dcd |
326 | |
12b3e9a3 |
327 | or C<starman> |
32d29dcd |
328 | |
12b3e9a3 |
329 | starman my_web_simple_app.pl |
330 | |
331 | =head2 to_psgi_app |
332 | |
333 | This method is called by L</run_if_script> to create the L<PSGI> app coderef |
334 | for use via L<Plack> and L<plackup>. If you want to globally add middleware, |
335 | you can override this method: |
6a4808bf |
336 | |
337 | use Web::Simple 'HelloWorld'; |
338 | use Plack::Builder; |
339 | |
340 | { |
341 | package HelloWorld; |
342 | |
343 | |
344 | around 'to_psgi_app', sub { |
345 | my ($orig, $self) = (shift, shift); |
346 | my $app = $self->$orig(@_); |
347 | builder { |
348 | enable ...; ## whatever middleware you want |
349 | $app; |
350 | }; |
351 | }; |
352 | } |
353 | |
12b3e9a3 |
354 | This method can also be used to mount a Web::Simple application within |
355 | a separate C<*.psgi> file - |
356 | |
357 | use strictures 1; |
358 | use Plack::Builder; |
359 | use WSApp; |
360 | use AnotherWSApp; |
361 | |
362 | builder { |
363 | mount '/' => WSApp->to_psgi_app; |
364 | mount '/another' => AnotherWSApp->to_psgi_app; |
365 | }; |
366 | |
367 | This method can be called as a class method, in which case it implicitly |
368 | calls ->new, or as an object method ... in which case it doesn't. |
32d29dcd |
369 | |
370 | =head2 run |
371 | |
30e2c525 |
372 | Used for running your application under stand-alone CGI and FCGI modes. |
32d29dcd |
373 | |
ca30a017 |
374 | I should document this more extensively but run_if_script will call it when |
375 | you need it, so don't worry about it too much. |
376 | |
377 | =head2 run_test_request |
378 | |
15928515 |
379 | my $res = $app->run_test_request(GET => '/' => %headers); |
ca30a017 |
380 | |
15928515 |
381 | my $res = $app->run_test_request(POST => '/' => %headers_or_form); |
ca30a017 |
382 | |
383 | my $res = $app->run_test_request($http_request); |
384 | |
385 | Accepts either an L<HTTP::Request> object or ($method, $path) and runs that |
386 | request against the application, returning an L<HTTP::Response> object. |
387 | |
388 | If the HTTP method is POST or PUT, then a series of pairs can be passed after |
389 | this to create a form style message body. If you need to test an upload, then |
390 | create an L<HTTP::Request> object by hand or use the C<POST> subroutine |
391 | provided by L<HTTP::Request::Common>. |
392 | |
8c3623e2 |
393 | If you prefix the URL with 'user:pass@' this will be converted into |
394 | an Authorization header for HTTP basic auth: |
395 | |
396 | my $res = $app->run_test_request( |
397 | GET => 'bob:secret@/protected/resource' |
398 | ); |
399 | |
15928515 |
400 | If pairs are passed where the key ends in :, it is instead treated as a |
401 | headers, so: |
402 | |
403 | my $res = $app->run_test_request( |
404 | POST => '/', |
405 | 'Accept:' => 'text/html', |
406 | some_form_key => 'value' |
407 | ); |
408 | |
409 | will do what you expect. You can also pass a special key of Content: to |
410 | set the request body: |
411 | |
412 | my $res = $app->run_test_request( |
413 | POST => '/', |
414 | 'Content-Type:' => 'text/json', |
415 | 'Content:' => '{ "json": "here" }', |
416 | ); |
417 | |
7e103e8e |
418 | =head1 AUTHORS |
32d29dcd |
419 | |
7e103e8e |
420 | See L<Web::Simple> for authors. |
32d29dcd |
421 | |
7e103e8e |
422 | =head1 COPYRIGHT AND LICENSE |
32d29dcd |
423 | |
7e103e8e |
424 | See L<Web::Simple> for the copyright and license. |
32d29dcd |
425 | |
426 | =cut |