Index: [Article Count Order] [Thread]

Date: Thu, 18 Dec 2003 19:25:16 +0900 (JST)
From: GOTOU Yuuzou <gotoyuzo@notwork.org>
Subject: [webrickja:94] Re: wrapper for CGI env.
To: webrickja@notwork.org
Message-Id: <20031218.192516.24444253.gotoyuzo@kotetsu.does.notwork.org>
In-Reply-To: <20031217134311.30B483544A@arika.org>
References: <20031217134311.30B483544A@arika.org>
X-Mail-Count: 00094

In message <20031217134311.30B483544A@arika.org>,
 `akira yamada <akira@arika.org>' wrote:
> とある会話がきっかけで
> CGI環境をWEBrickのHTTPRequestとHTTPResponseで
> wrapするスクリプトを作りました。

おもしろいと思います。
HTTPServlet::AbstractServlet のように do_XXXX を再定義して使
うクラスを作ってみましたが、なかなか使いやすそうです。
# config の引き回し方がちょっとダメな感じですが。

> 後付けのねらいとしては
> cgi.rbを使わないCGIスクリプティングを目指す
> というところかなあと考えています。
> 
> WEBrickでどうこうするようなコードではないかもしれませんが
> もし興味をもたれた方がいらっしゃいましたら
> コメントをいただけるとうれしいです。

例えば、webrick/cgi.rb として追加してもいいと思いますが、ど
うでしょうね。

-- 
ごとうゆうぞう

require "cgiwrap"

module WEBrick
  class CGI
    def self.start(config, *options)
      WEBrick::CGISocket.wrap(config){|sock, req, res|
        begin
          cgi = self.new(config, *options)
          cgi.service(req, res)
        rescue HTTPStatus::Error => ex
          res.set_error(ex)
        rescue HTTPStatus::Status => ex
          res.status = ex.code
        rescue StandardError => ex 
          @logger.error(ex)
          res.set_error(ex, true)
        ensure
          res.send_response(sock)
        end
      }
    end

    def initialize(config, *options)
      @config = config
      @logger = config[:Logger]
      @options = options
    end

    def service(req, res)
      method_name = "do_" + req.request_method.gsub(/-/, "_")
      if respond_to?(method_name)
        __send__(method_name, req, res)
      else  
        raise HTTPStatus::MethodNotAllowed,
              "unsupported method `#{req.request_method}'."
      end
    end
  end 
end  

require "pp"
      
class MyCGI < WEBrick::CGI
  def do_GET(req, res)
    res['content-type'] = 'text/plain; charset=iso-8859-1'
    res.chunked = true if req.http_version > '1.0'
     
    res.body =  "Request:\n"
    res.body << PP::pp(req, "", 80)
    res.body << "\n"
    res.body << "Response:\n"
    res.body << PP::pp(res, "", 80)
  end
end

MyCGI.start(WEBrick::Config::HTTP)