Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Getting or Setting the Request Method

You need to get or set the method used for the request.

Technique

Use the method() and method_number() methods from the Apache class.

use Apache::Constants qw(:methods NOT_FOUND);

use strict;

sub handler {

 my $r = shift;
 
 if ($r->method_number == M_POST) {

  # Stash away the POST data.
  my $content = $r->content;

  # Now, change the request to a GET...
  $r->method('GET');
  $r->method_number(M_GET);
  $r->headers_in->unset('Content-Length');

  # ... and repopulate the query string with the POST data.
  $r->args($content);

 }

 # Now, the custom response can use the POST data.
 $r->custom_response(NOT_FOUND, '/perl-bin/docked.pl');

 # Continue along...
}

Comments

There are times when you need to get or set the method used for a request, such as GET, POST, or HEAD. In such cases, you should also set the method number as well, as shown in the sample code. The method number is an internal constant used by the Apache API, and is available using the :methods import tag with Apache::Constants. The method numbers are then referred to as M_GET, M_POST, M_PUT, and M_DELETE.

Requests that originate with the HEAD method are handled specially by Apache. When a HEAD request is received, the method number is set to M_GET and the header_only() flag within the request record is set to true. You will often see the following in a handler:

sub handler {

  my $r = shift;

  $r->send_http_header('text/html');

  # Don't generate content on a HEAD request.
  return OK if $r->header_only;

  # Continue along...
}

which honors HEAD requests by returning just the headers.

One common programmatic problem whose solution involves setting the request method is redirection of POST requests. The subtlety that arises here is that data sent via POST can be read in from the socket only once, and so must be stored somehow for later use. The solution handler snippet addresses this issue. Here, we change the method and method number to those appropriate for a GET request. We then unset the Content-Length header and populate the contents of the URI query string through the args() method. Now, our custom response can have access to any form fields submitted via a POST request.

  • + Share This
  • 🔖 Save To Your Account