2006-11-14
■ [Ruby] WEBrickできみにも書けるWebサーバ

Python と Twisted できみにも書ける Web サーバとperl - HTTP::Daemonできみにも書けるWebサーバにインスパイアされてみたよ。
require 'webrick' document_root = 'C:/inetpub/wwwroot/' server = WEBrick::HTTPServer.new({ :DocumentRoot => document_root, :BindAddress => '0.0.0.0', :Port => 10080 }) ['INT', 'TERM'].each {|signal| Signal.trap(signal){ server.shutdown } } server.start
document_rootは環境に合わせて変更してね。これをwebserver.rbとして保存して、あとは適当にindex.htmlファイルをdocument_rootで指定したフォルダに
<html> <head> <title>Hello</title> </head> <body> Hello, Ruby! </body> </html>
という内容で作成したあと、コマンドプロンプトで
>ruby webserver.rb
という感じで起動して、Webブラウザでhttp://127.0.0.1:10080/にアクセスして試してね。
もちろんCGIも動かすことができるよ。たとえばさっきのwebserver.rbを
require 'webrick' document_root = 'C:/inetpub/wwwroot/' rubybin = 'C:/ruby/bin/ruby.exe' server = WEBrick::HTTPServer.new({ :DocumentRoot => document_root, :BindAddress => '0.0.0.0', :CGIInterpreter => rubybin, :Port => 10080 }) ['/cgi-bin/hello.rb'].each {|cgi_file| server.mount(cgi_file, WEBrick::HTTPServlet::CGIHandler, document_root + cgi_file) } ['INT', 'TERM'].each {|signal| Signal.trap(signal){ server.shutdown } } server.start
のように変更して(rubybinは環境に合わせて変更してね)、
require 'cgi' cgi = CGI.new('html3') cgi.out { cgi.html { cgi.head { cgi.title{'Hello'} } + cgi.body { 'Hello, Ruby!' } } }
という内容のhello.rbをdocument_rootフォルダの下のcgi-binフォルダに作成して、Webブラウザでhttp://127.0.0.1:10080/cgi-bin/hello.rbにアクセスして試してね。
webサーバがない環境でも、Rubyさえインストールされていればこんな感じでちょっとしたCGIを試してみることができるから便利だよ。
追記:WEBrick上でHikiやtDiaryを動かしてみたよ!参考にしてね。
コメント
トラックバック - http://rubyist.g.hatena.ne.jp/muscovyduck/20061114