summaryrefslogtreecommitdiffstats
path: root/lib/Plack/Client/Backend/psgi_local.pm
blob: 7bb9bcc436eacdd0c7541555bb5b0b6b538536e0 (plain) (blame)
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
package Plack::Client::Backend::psgi_local;
use strict;
use warnings;
# ABSTRACT: backend for handling local app requests

use Carp;
use Plack::Middleware::ContentLength;

use base 'Plack::Client::Backend';

=head1 SYNOPSIS

  Plack::Client->new(
      'psgi-local' => {
          apps => { myapp => sub { ... } },
      },
  );

  Plack::Client->new(
      'psgi-local' => Plack::Client::Backend::psgi_local->new(
          apps => { myapp => sub { ... } },
      ),
  );

=head1 DESCRIPTION

This backend implements requests made against local PSGI apps.

=cut

=method new

Constructor. Takes a hash of arguments, with these keys being valid:

=over 4

=item apps

A mapping of local app names to PSGI app coderefs.

=back

=cut

sub new {
    my $class = shift;
    my %params = @_;
    my $self = $class->SUPER::new(@_);

    croak 'apps must be a hashref'
        if ref($params{apps}) ne 'HASH';

    $self->{apps} = $params{apps};

    return $self;
}

sub _apps { shift->{apps} }

=method app_for

Returns the PSGI app coderef for the given app name.

=cut

sub app_for {
    my $self = shift;
    my ($for) = @_;
    return $self->_apps->{$for};
}

=method app_from_request

Takes a L<Plack::Request> object, and returns the app corresponding to the app
corresponding to the app name given in the C<authority> section of the given
URL.

=cut

sub app_from_request {
    my $self = shift;
    my ($req) = @_;

    my $app_name;
    if (my $uri = $req->env->{'plack.client.original_uri'}) {
        $app_name = $uri->authority;
    }
    else {
        $app_name = $req->uri->authority;
        $app_name =~ s/(.*):.*/$1/; # in case a port was added at some point
    }

    my $app = $self->app_for($app_name);
    croak "Unknown app: $app_name" unless $app;
    return Plack::Middleware::ContentLength->wrap($app);
}

1;