# * George Moschovitis # (c) 2004-2005 Navel, all rights reserved. # $Id$ require 'webrick' require 'glue/flexob' require 'nitro/context' require 'nitro/dispatcher' module WEBrick class HTTPRequest attr :socket end class HTTPResponse def header=(header) @header = header end def cookies=(cookies) @cookies = cookies end end end module N # Helper methods for the WebrickAdapter. class Webrick class << self attr_accessor :server def start(conf) conf = Conf.new(conf) unless conf.is_a?(Conf) # patch for OSX Socket.do_not_reverse_lookup = true if :none == conf.log and RUBY_PLATFORM !~ /mswin32/ accesslog = WEBrick::BasicLog::new('/dev/null') refererlog = WEBrick::BasicLog::new('/dev/null') elsif (conf.accesslog || conf.refererlog) accesslog = WEBrick::BasicLog::new(conf.accesslog || 'log/access.log') refererlog = WEBrick::BasicLog::new(conf.refererlog || 'log/referer.log') else accesslog = STDERR refererlog = STDERR end @server = WEBrick::HTTPServer.new( :BindAddress => conf.host, :Port => conf.port, :DocumentRoot => conf.dispatcher.public_root, :AccessLog => [ [accesslog, WEBrick::AccessLog::COMMON_LOG_FORMAT], [refererlog, WEBrick::AccessLog::REFERER_LOG_FORMAT] ] ) trap('INT') { @server.shutdown } @server.mount('/', WebrickAdapter, conf) @server.start end end end # A Webrick Adapter for Nitro. #-- # TODO: optimize the conversion from WEBrick's # parameters to the Nitro parameters. #++ class WebrickAdapter < WEBrick::HTTPServlet::AbstractServlet # REQUEST_MUTEX = Mutex.new def initialize(server, conf) @conf = conf # Handles static resources. Useful when running # a stand-alone webrick server. @file_handler = WEBrick::HTTPServlet::FileHandler.new( server, conf.dispatcher.public_root, conf.webrick_options || {}) end def handle(req, res) path = req.request_uri.path if path =~ /\./ @file_handler.do_GET(req, res) else # gmosx, TODO: move this into a filter. Og.db.get_connection if defined?(Og) and Og.db # REQUEST_MUTEX.lock context = Context.new(@conf) context.headers = {} req.header.each { |h, v| context.headers[h.upcase] = v.first } context.headers.update(req.meta_vars) context.params = {} req.query.each do |k, v| if k =~ /(.*)\[\]$/ context.params[k] = v else context.params[k] = v.to_s end end # context.in = req.socket # CgiUtils.parse_params(context) #context.cookies = {} #req.cookies.each { |c| context.cookies[c.name] = c.value } CgiUtils.parse_cookies(context) context.render(path) res.status = context.status res.header = context.response_headers || {} res.cookies = context.response_cookies || {} res.body = context.out context.close end ensure # REQUEST_MUTEX.unlock if REQUEST_MUTEX.locked? Og.db.put_connection if defined?(Og) and Og.db end alias do_GET handle alias do_POST handle end end