jacques has asked for the wisdom of the Perl Monks concerning the following question:

In my CGI script, I have a function that prints an HTML page to stdout. The function is imported from a custom module. I want to show the HTTP response headers in the HTML page.

I can easily show the request headers from printing the server environment variables in the HTML, but it is the response headers that ellude me.

I looked at HTTP::Response. But to use HTTP::Response, I would have to initiate a new request. If I make a fresh request in the module and capture the response, then that response would be different from the one involving the HTML page.

Note: any code would be in my module and not in the CGI script. Don't try to solve this in the CGI script (the caller's namespace). For example:

Package My::Module; require Exporter; @My::Module::ISA = qw(Exporter); @My::Module::EXPORT = qw(the-function); sub the-function { print "Content-type: text/html\n\n"; print <<HTML; Here are the HTTP REQUEST headers: <p> HTTP Request: $ENV{'REQUEST_METHOD'} $0 $ENV{'SERVER_PROTOCOL'} <br> Host: $ENV{'HTTP_HOST'} <br> User-Agent: $ENV{'HTTP_USER_AGENT'} <br> Accept: $ENV{'HTTP_ACCEPT_ENCODING'} <br> Accept-Language: $ENV{'HTTP_ACCEPT_LANGUAGE'} <br> Accept-Charset: $ENV{'HTTP_ACCEPT_CHARSET'} <br> Keep-Alive: $ENV{'HTTP_KEEP_ALIVE'} <br> Connection: $ENV{'HTTP_CONNECTION'} <p> SORRY -- I don't know how to show you the HTTP --RESPONSE-- Headers . +. . HTML } 1; Package Main; #!/usr/bin/perl use My::Module; the-function(); __END__
I hope the code makes my question clearer.

Replies are listed 'Best First'.
Re: Showing HTTP response headers
by borisz (Canon) on Jan 08, 2005 at 19:08 UTC
    Use a proxy to log request and/or response headers. For example HTTP::Proxy.
    Boris
Re: Showing HTTP response headers
by BUU (Prior) on Jan 08, 2005 at 19:03 UTC
    Response headers can be added by any part of the system at basically any time (Unless you've sent a blank line already), so basically you are stuck. If you can some how arrange for your module to be loaded before any headers are sent, you could tie STDOUT and capture the headers before sending them off.
      Response headers can be added by any part of the system at basically any time (Unless you've sent a blank line already), so basically you are stuck.
      And proxies can add even more headers while forwarding the response... Depending on what the OP wants, using firefox with the live HTTP headers plugin can be used to display the headers as they arrive at the browser.

      Otherwise you might also be able to capture the STDOUT output of the called subroutines (if it doesn't use STDOUT explicitly):

      #!/usr/local/bin/perl -w use strict; sub prints_headers { print "Content-type: text/html\n\n"; } my $output; open my $NEWSTDOUT,">",\$output; select $NEWSTDOUT; prints_headers(); select STDOUT; print "Captured '$output'\n";
        I have added code to my original post to make my question clearer.