1 package Web::Simple::Application;
5 has 'config' => (is => 'ro', trigger => sub {
6 my ($self, $value) = @_;
7 my %default = $self->_default_config;
8 my @not = grep !exists $value->{$_}, keys %default;
9 @{$value}{@not} = @default{@not};
12 sub _setup_default_config {
16 if (${"${class}::_default_config"}{CODE}) {
17 $class->_cannot_call_twice('_setup_default_config', 'default_config');
20 my @defaults = (@_, $class->_default_config);
23 *{"${class}::_default_config"} = sub { @defaults };
27 sub _default_config { () }
29 sub _construct_response_filter {
30 my ($class, $code) = @_;
31 my $self = do { no strict 'refs'; ${"${class}::self"} };
32 require Web::Dispatch::Wrapper;
33 Web::Dispatch::Wrapper->from_code(sub {
34 my @result = $_[1]->($_[0]);
36 $self->_run_with_self($code, @result);
43 sub _construct_redispatch {
44 my ($class, $new_path) = @_;
45 require Web::Dispatch::Wrapper;
46 Web::Dispatch::Wrapper->from_code(sub {
47 $_[1]->({ %{$_[0]}, PATH_INFO => $new_path });
51 sub _build_dispatch_parser {
52 require Web::Dispatch::Parser;
53 return Web::Dispatch::Parser->new;
56 sub _cannot_call_twice {
57 my ($class, $method, $sub) = @_;
58 my $error = "Cannot call ${method} twice for ${class}";
60 $error .= " - did you call Web::Simple's ${sub} export twice?";
65 sub _setup_dispatcher {
66 my ($class, $dispatcher) = @_;
69 if (${"${class}::_dispatcher"}{CODE}) {
70 $class->_cannot_call_twice('_setup_dispatcher', 'dispatch');
75 *{"${class}::dispatch_request"} = $dispatcher;
79 sub _build_final_dispatcher {
80 [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
84 my ($self, $run, @args) = @_;
85 my $class = ref($self);
87 local *{"${class}::self"} = \$self;
92 # ->as_psgi_app is true for require() but also works for plackup
93 return $_[0]->as_psgi_app if caller(1);
94 my $self = ref($_[0]) ? $_[0] : $_[0]->new;
100 require Plack::Server::CGI;
101 Plack::Server::CGI->run($self->as_psgi_app);
106 require Plack::Server::FCGI;
107 Plack::Server::FCGI->run($self->as_psgi_app);
111 my $self = ref($_[0]) ? $_[0] : $_[0]->new;
112 require Web::Dispatch;
113 require Web::Simple::DispatchNode;
114 my $final = $self->_build_final_dispatcher;
116 app => sub { $self->dispatch_request(@_), $final },
117 node_class => 'Web::Simple::DispatchNode',
118 node_args => { app_object => $self }
124 if ($ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}) {
125 return $self->_run_fcgi;
126 } elsif ($ENV{GATEWAY_INTERFACE}) {
127 return $self->_run_cgi;
129 unless (@ARGV && $ARGV[0] =~ m{^/}) {
130 return $self->_run_cli(@ARGV);
133 my $path = shift @ARGV;
135 require HTTP::Request::Common;
137 local *GET = \&HTTP::Request::Common::GET;
139 my $request = GET($path);
141 Plack::Test::test_psgi($self->as_psgi_app, sub { $response = shift->($request) });
142 print $response->as_string;
147 die $self->_cli_usage;
151 "To run this script in CGI test mode, pass a URL path beginning with /:\n".