CommonThread

Mongrel web framework starter kit

Posted by anthony crumley, Tue Nov 06 07:24:00 UTC 2007

Mongrel is a sweet little Ruby based web server. A number of frameworks already run on top of it, Ruby on Rails, Merb, Og + Nitro, Camping, and IOWA. It is actually quite easy to get started once you figure out what to do. Unfortunately the documentation is a bit sparse. On the bright side, all the frameworks mentioned above are open source so there are plenty of examples. These examples are a bit complex so I will try to give you the minimum required to get started.

Put the following code in a file named server.rb.
require 'rubygems'
require 'mongrel'
require 'framework_handler'

config = Mongrel::Configurator.new :host => '127.0.0.1' do
  listener :port => 4000 do
    uri "/", :handler => FrameworkHandler.new
  end
  trap("INT") { stop }
  run
end
config.join

When server.rb is run it will set up a mongrel server at http://localhost:4000. Any url accessed on this server will simply invoke the framework handler described next.

Put the following code in a file named framework_handler.rb.
class FrameworkHandler < Mongrel::HttpHandler
  def process(request, response)
    response.start(200) do |head, out|
      head["Content-Type"] = "text/html" 
      out.write "Hello from " 
      out.write request.params[Mongrel::Const::REQUEST_URI]
    end
  end
end

When a url is accessed on the server this handler will display a message including the uri. If the address http://localhost:4000/ruby/land is accessed then the result will be “Hello from /ruby/land”

As with all starter kits, this just gets you started. Finishing is up to you. Have fun!!

Filed Under: | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.




Categories