perlhashplackpsgi

Set custom environment variable to psgi hash plack


When I do a request to dumper $env I get all data of enviromment hash psgi, in this example

sub { 
  my $env = shift;  
  return [ 200, [], [ $env->{REMOTE_ADDR} ] ];  
}

or more directly

sub { 
  return [ 200, [], [ shift->{REMOTE_ADDR} ] ];   
}

Output:

Returns the IP address of the client

How I can set my own custom environment variable to psgi hash plack ?

why I want to do that, my case is relation to: Nginx variables similar to SetEnv in Apache?

If not possible to do that, can I create subclass and add that functionality to psgi web server ?

Thanks for your time


Solution

  • Assuming you want to set variables within the application server, this looks like the perfect case for some plack middleware. For this case, I found Plack::Middleware::ReviseEnv, which is usable within your app.psgi:

    # app.psgi
    use Plack::Builder;
    
    my $app = sub {
        return [ 200, [], [ shift->{var} ] ];
    };
    
    builder {
        enable "ReviseEnv", revisors => { 'var'  => 'custom',
                                          'var2' => 'other' };
        $app;
    };
    

    The documentation also lists additional options for setting values beyond simple text, such as including other $env data or %ENV environment variables.