Re: A simple mod_ruby file handler example

Shugo Maeda <[email protected]> Thu, 28 Apr 2005 12:23:14 +0900
Newsgroups gmane.comp.apache.mod-ruby
Message-ID <[email protected]>
Hi,

Clayton Cottingham wrote:
> New to ruby/mod_ruby
> 
> Trying to figure out how to make a simple mod_ruby filehandle

Is this what you want?

=begin

= apache/file-handler.rb

Copyright (C) 2005  Shugo Maeda <[email protected]>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

== Overview

Apache::FileHandler handles static files.

== Example of httpd.conf

  RubyRequire apache/file-handler
  <Location /files>
  SetHandler ruby-object
  RubyHandler Apache::FileHandler.instance
  </Location>

=end

require "singleton"

module Apache
  class FileHandler
    include Singleton

    def handler(r)
      begin
        r.content_type = "text/plain"
        filename = r.filename.dup.untaint
        r.print(File.read(filename))
        return OK
      rescue Errno::ENOENT
        return NOT_FOUND
      rescue Errno::EPERM, Errno::EISDIR
        return FORBIDDEN
      end
    end
  end
end