Build your own internet home yourself with WEBrick

The amazing Bob the Builder I’ve been playing with WEBrick yesterday night and found it pretty easy to use. Here are a couple of my discoveries.

First, you don’t need to download any gem, webrick is part of ruby core! How cool is that ?

To start a new http server:

require 'webrick'
s =
  :Port            => 2000,
  :DocumentRoot    => Dir::pwd

trap("INT") { s.shutdown }

and go to http://localhost:2000

That might soon get boring, add a little more dynamic!

include WEBrick
s = => 2000)

class HelloServlet  < HTTPServlet::AbstractServlet
  def do_GET(req, res)
    res.body = "<HTML>hello, world from #{req.path}.</HTML>"
    res['Content-Type'] = "text/html"
s.mount("/hello", HelloServlet)

trap("INT") { s.shutdown }

try http://localhost:2000/hello or http://localhost:2000/hello/bob

Starting to see the picture ?

You could also mix static http file service with servlets:

class MixedUpServlet  < WEBrick::HTTPServlet::DefaultFileHandler
  def initialize(server, my_app)
    super(server, my_app)
    @my_app = my_app
  def service(req, resp)
    if /(\w+).action$/ =~ req.path
      res['Content-Type'] = "text/html"
      res.body = @my_app.send $1
      @local_path = Dir::pwd + "/#{req.path}"
      do_GET(req, resp)
s.mount("/", MixedUpServlet, my_app)

Now any request to something.action will call the corresponding my_app method any other file will be served as usual.

Hope you have as much fun as I had playing with this and let me know what you come up with !

Small footnote: this code is not safe to be used as is on todays freaky-dangerous-not-safe internet! Do not copy-paste and deploy. If you’re serious about building your application from the ground up, I suggess you take a look at Mongrel which offers much better performance.


1 Comment

Filed under ruby

One response to “Build your own internet home yourself with WEBrick

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s