Rubyでhttpサーバー
プログラミングRuby 第2版 言語編を読んでいてRubyでWEBrickを使用するとhttpサーバーを作ることができるということを知ったので実験。
後述のサイトを参考にして、/home/zaurus/Documents/ruby/webrickを基準ディレクトリして、ここにサーバースクリプトを置きログもここに作成。htmlサブディレクトリを作成してDocumentRootに指定、ここにindex.htmlを置く。またcgiスクリプトをcgi-binサブディレクトリに置く。ポートを2000にした。
/home/zaurus/Documents/ruby/webrick/httpd.rb /html/index.html /cgi-bin/test.cgi
起動は
$ cd /home/zaurus/Documents/ruby/webrick $ ./httpd.rb &
停止はpsでpidを調べてkillする(もっと良い方法がありそう)
起動後webブラウザで以下のURLを閲覧するとhtmlファイルやcgiスクリプトの出力を表示
http://localhost:2000/ http://localhost:2000/cgi-bin/test.cgi
なんかすごく簡単にhttpサーバーが出来てしまって驚きました。多分動作はapache等と比べると遅いとは思いますが、ちょっとした実験なんかには十分使用できると思います。WEBrickはもっといろいろなことが出来そうですが初心者向けのマニュアルが見つからないのと、httpの知識が無いので難しいかなぁ。
httpd.rb
access_log_streamがcloseしてないのが、ちと気持ち悪いです。
#!/usr/bin/env ruby require 'webrick' include WEBrick PATH = '/home/zaurus/Documents/ruby/webrick' def start_webrick( config = {} ) # config.update server = HTTPServer.new(config) yield server if block_given? ['INT', 'TERM'].each do |signal| trap(signal) { server.shutdown } end server.start end access_log_stream = File.open("#{PATH}/access.log", 'w') cgi_dir = PATH + '/cgi-bin' start_webrick( :DocumentRoot => PATH + '/html' , :Port => 2000 , :Logger => WEBrick::Log.new('sys.log', WEBrick::Log::DEBUG) , :AccessLog => [[access_log_stream, AccessLog::COMBINED_LOG_FORMAT]] ){ |server| server.mount('/cgi-bin', HTTPServlet::FileHandler, cgi_dir, {:FancyIndexing => true}) }
index.html
<html> <head> <title>Title</title> </head> <body> Hello Ruby HTTPServer World<br> <p> </body> </html>