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