[Mongrel] Howto write a mongrel handler for a CGI app using CGIWrapper

Simon Rozet
Fri, 04 Jan 2008 08:23:44 -0000

Hello,

Just for further reference in case of someone else want to do the same :

I wanted to write a mongrel for a CGI app :
[[[
require ''cgi''
require ''foo''

cgi = CGI.new

if !cgi[''uri''] || (cgi[''uri''] ==
'''')
  Foo.error "URI argument is required"
end

uri = cgi[''uri'']
user = cgi[''username'']
pass = cgi[''password'']

foo = Foo.new(:output => ''html'')

if user == ''''
  foo.check(uri)
else
  foo.check(uri, user, pass)
end
foo.report
]]]

Here is the mongrel version, using Mongrel::CGIWrapper :
[[[
require ''mongrel''
require ''cgi''
require ''foo''

class AppHandler < Mongrel::HttpHandler
  def process(request, response)
    cgi = Mongrel::CGIWrapper.new(request, response)

    if !cgi[''uri''] || (cgi[''uri''] ==
'''')
      response.start(200, true) do |header, body|

        Foo.error("URI argument is required", output=body)
      end
    end

    format = request.params[''HTTP_ACCEPT''] ==
''text/plain'' ? ''text'' :
''html''
    ape = Ape.new({ :crumbs => true, :output => format })

    if cgi[''user''] && cgi[''pass'']
      ape.check(cgi[''uri''], cgi[''user''],
cgi[''pass''])
    else
      ape.check(cgi[''uri''])
    end

    response.start(200, true) do |head, body|
      ape.report(output=body)
    end
  end
end

h = Mongrel::HttpServer.new(''0.0.0.0'', 4000)
h.register(''/'',
Mongrel::RedirectHandler.new(''/ape/index.html''))
h.register(''/ape'',
Mongrel::DirHandler.new(File.dirname(__FILE__) +
''/layout'', true))
h.register(''/atompub/go'', ApeHandler.new)
h.run.join
]]]

--
Simon Rozet <simon at rozet.name>