Plack::Middleware::Proxy::AddVia - Adds the Via header for the current host.


Plack-App-Proxy documentation Contained in the Plack-App-Proxy distribution.

Index


Code Index:

NAME

Top

Plack::Middleware::Proxy::AddVia - Adds the Via header for the current host.

SYNOPSIS

Top

  use Plack::Builder;
  use Plack::App::Proxy;

  builder {
      enable "Proxy::AddVia";
      Plack::App::Proxy->new(host => "http://10.0.1.2:8080/")->to_app;
  };

DESCRIPTION

Top

Plack::Middleware::Proxy::AddVia adds the Via header to the request and response, like mod_proxy's ProxyVia option.

AUTHOR

Top

Masahiro Honma <hiratara@cpan.org>

SEE ALSO

Top

Plack::App::Proxy


Plack-App-Proxy documentation Contained in the Plack-App-Proxy distribution.

package Plack::Middleware::Proxy::AddVia;
use strict;
use parent 'Plack::Middleware';

use Plack::Util;

our $VERSION = '0.01';

sub add_via {
    my ( $self, $via, $protocol, $recieved_by ) = @_;

    $protocol =~ s|^HTTP/||;
    return join ', ', $via || (), "$protocol $recieved_by";
}

sub make_recieved_by_from_env {
    my ( $self, $env ) = @_;
    my $host = $env->{SERVER_NAME} . (
        $env->{SERVER_PORT} == 80 ? '' : ":$env->{SERVER_PORT}"
    ) ;
    return  $host . " (" . __PACKAGE__ . "/$VERSION)";
}

sub call {
    my($self, $env) = @_;

    my $recieved_by = $self->make_recieved_by_from_env( $env );

    $env->{HTTP_VIA} = $self->add_via( 
        $env->{HTTP_VIA}, $env->{SERVER_PROTOCOL}, $recieved_by
    );

    return sub {
        my $orig_respond = shift;

        my $respond = sub {
            my $res = shift;
            my $via = Plack::Util::header_get($res->[1], 'Via');
            Plack::Util::header_set(
                $res->[1], 'Via' => $self->add_via(
                    $via, $env->{'plack.proxy.last_protocol'}, $recieved_by
                )
            );
            return $orig_respond->( $res );
        };

        my $res = $self->app->($env);
        ref $res eq 'CODE' ? $res->( $respond ) : $respond->( $res );
    };
}

1;

__END__