home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Writing Apache Modules with Perl and C
By:   Lincoln Stein and Doug MacEachern
Published:   O'Reilly & Associates, Inc.  - March 1999

Copyright © 1999 by O'Reilly & Associates, Inc.


 


   Show Contents   Previous Page   Next Page

Chapter 4 - Content Handlers
Virtual Documents

The previous sections of this chapter have been concerned with transforming existing files. Now we turn our attention to spinning documents out of thin air. Despite the fact that these two operations seem very different, Apache content handlers are responsible for them both. A content handler is free to ignore the translation of the URI that is passed to it. Apache neither knows nor cares that the document produced by the content handler has no correspondence to a physical file.

We've already seen an Apache content handler that produces a virtual document. Chapter 2, A First Module, gave the code for Apache::Hello, an Apache Perl module that produces a short HTML document. For convenience, we show it again in Example 4-7. This content handler is essentially identical to the previous content handlers we've seen. The main difference is that the content handler sets the MIME content type itself, calling the request object's content_type() method to set the MIME type to type text/html. This is in contrast to the idiom we used earlier, where the handler allowed Apache to choose the content type for it. After this, the process of emitting the HTTP header and the document itself is the same as we've seen before.

After setting the content type, the handler calls send_http_header() to send the HTTP header to the browser, and immediately exits with an OK status code if header_only() returns true (this is a slight improvement over the original Chapter 2 version of the program). We call get_remote_host() to get the DNS name of the remote host machine, and incorporate the name into a short HTML document that we transmit using the request object's print() method. At the end of the handler, we return OK.

There's no reason to be limited to producing virtual HTML documents. You can just as easily produce images, sounds, and other types of multimedia, provided of course that you know how to produce the file format that goes along with the MIME type.

Example 4-7. "Hello World" Redux

package Apache::Hello;
# file: Apache/Hello.pm
use strict;
use Apache::Constants qw(:common);
sub handler {
   my $r = shift;
   $r->content_type('text/html');
   $r->send_http_header;
   return OK unless $r->header_only;
   my $host = $r->get_remote_host;
   $r->print(<<END);
<HTML>
<HEAD>
<TITLE>Hello There</TITLE>
</HEAD>
<BODY>
<H1>Hello $host</H1>
"Hello world" is a terribly overused phrase in programming books,
don't you think?
</BODY>
</HTML>
END
   return OK;
}
1;
   Show Contents   Previous Page   Next Page
Copyright © 1999 by O'Reilly & Associates, Inc.