Index: [Article Count Order] [Thread]

Date: Sun, 12 Oct 2003 04:06:29 +0900 (JST)
From: GOTOU Yuuzou <gotoyuzo@notwork.org>
Subject: [webricken:124] Re: documentation, and virtual servers
To: webricken@notwork.org
Message-Id: <20031012.040629.879494168.gotoyuzo@kotetsu.does.notwork.org>
In-Reply-To: <20031010145920.GB12686@jasonandali.org.uk>
References: <20031010145920.GB12686@jasonandali.org.uk>
X-Mail-Count: 00124

In message <20031010145920.GB12686@jasonandali.org.uk>,
 `Jason Williams <jason@jasonandali.org.uk>' wrote:
> Firstly, is there any documentation for webrick other than the
> sparse examples at http://www.webrick.org/ ?

Other than it, some articles are found in the archive of
ruby-talk list.  Sorry, any documentation is not available
yet..

> Secondly, how do I create a webrick server that will do
> "virtual hosting" (ie, run different handlers for different
> hostnames)?

It becomes possible by adding bits of extension to HTTPServer.
This may be a standard functionality. How do you think?

-- 
require 'webrick'

module WEBrick
  class VirtualHostServer < HTTPServer
    def initialize(config)
      super(config)
      @virtual_hosts = []
    end

    def virtual_host(server)
      @virtual_hosts << server
    end

    def service(req, res)
      if server = lookup_server(req)
        server.service(req, res)
      else
        super
      end
    end

    def lookup_server(req) 
      @virtual_hosts.find{|server|
        (server[:Port].nil?        || req.port == server[:Port])           &&
        (server[:BindAddress].nil? || req.addr[3] == server[:BindAddress]) &&
        (server[:ServerName].nil?  || req.host == server[:ServerName])
      }
    end
  end
end

## build default server
svr = WEBrick::VirtualHostServer.new(
  :Port         => 10080,
  :BindAddress  => "0.0.0.0"
)
svr.mount_proc("/"){|req, res|
  res.body = "This is default server!"
  res['content-type'] = "text/plain"
}

## build a virtual server for "localhost"
localhost = WEBrick::HTTPServer.new(
  :DoNotListen => true,        # don't forget!
  :Port        => nil,
  :BindAddress => nil,
  :ServerName  => "localhost"
)
localhost.mount_proc("/"){|req, res|
  res.body = "This is localhost!"
  res['content-type'] = "text/plain"
}

svr.virtual_host(localhost)
svr.start
-- 

regards,
-- 
gotoyuzo