WEBrick is a HTTP server library written by TAKAHASHI Masayoshi, GOTOU Yuuzou, along with patches contributed various Ruby users and developers. It started from an article entitled ``Internet Programming with Ruby'' in a Japanese network engineering magazine ``OpenDesign''. And now, it is part of the Ruby 1.8 standard library.
You can use WEBrick to create HTTP-based server or application. You may use also use it as a base for building web-application frameworks like IOWA, Tofu, and many others.
It can also be used to build non-HTTP server, like the Daytime Server example in the WEBrick home page, although that would be a pity since you would not be able to use WEBrick's support for the HTTP protocol.
In the web-application paradigm, WEBrick is quite low-level. It does not know about ``web application'', for starter. ``user interaction session'' is also a foreign concept.
All it knows are servlets. As far as it concerns, each servlet is independent from the others. If there are many servlets working together to provide a web application, guess who should provide the glue? You! If you want to track a user's interaction through the servlets, guess who should provide the code? You! If you need those functionalities, I recommend using IOWA or Tofu or others. Other people have took pain to provide that additional layers on top of WEBrick, so you do not have to re-invent the wheel.
# A simple WEBrick invocation
require 'webrick'
server = WEBrick::HTTPServer.new
#
# You would want to mount handlers here.
# Read further to know what
# handlers are.
#
# trap signals to invoke the shutdown procedure cleanly
['INT', 'TERM'].each { |signal|
trap(signal){ server.shutdown}
}
server.start
The above example will start WEBrick with the default configuration, including the configuration that tells it to listen on port 80. Now, let us try to override some of the configuration:
/var/www
To do the above, one would need to pass the appropriate configuration when instantiating the HTTPServer. Since for the rest
of this document we are going to modify the configuration and instantiate HTTPServer quite frequently, let us also ease that
process by defining a method that does all that.
require 'webrick'
include WEBrick # let's import the namespace so
# I don't have to keep typing
# WEBrick:: in this documentation.
def start_webrick(config = {})
# always listen on port 8080
config.update(:Port => 8080)
server = HTTPServer.new(config)
yield server if block_given?
['INT', 'TERM'].each {|signal|
trap(signal) {server.shutdown}
}
server.start
end
start_webrick(:DocumentRoot => '/var/www')
Output:
dede:~$ w3m -dump http://localhost:8080 Index of / Name Last modified Size ------------------------------------------------------------ Parent Directory 2004/07/18 06:51 - docbook-dsssl/ 2003/10/15 00:30 - pub/ 2004/05/24 15:46 - ------------------------------------------------------------ WEBrick/1.3.1 (Ruby/1.8.1/2004-02-03) at localhost:8080
2004-10-24