WEBrickでイッテみた。

前記事はこれ→実に久しぶりにオセロを弄る。


取りあえずwebrickって何?
って感じなのでココを参考にしてみた。→Rubyリファレンスマニュアル
っが、他のサイトに飛ばされココに着く→http://www.webrick.org/

で試しにこのページのExampleをコピペして、動作を読む。
(だって英文読むのシンドイ)

サーブレットのコード

Exampleには、HTTPサーバや、もっと一般的なサーバについて書いてあった。が今回は外部プログラム(思考エンジン)を実行するためのサーブレットがほしいので、Hello Servlet を参考にさせてもらった。


以下Example - webrick.orgのHello Servletのコード

#!/usr/local/bin/ruby
require 'webrick'
include WEBrick

s = HTTPServer.new( :Port => 2000 ) #ポート番号の指定

# HTTPServer#mount(path, servletclass)
#   When a request referring "/hello" is received,
#   the HTTPServer get an instance of servletclass
#   and then call a method named do_"a HTTP method".

class HelloServlet < HTTPServlet::AbstractServlet
  def do_GET(req, res)
    #ココから
    res.body = "<HTML>hello, world.</HTML>"
    res['Content-Type'] = "text/html" 
    #ココまでで、標準出力をする。  
  end
end
s.mount("/hello", HelloServlet)


# HTTPServer#mount_proc(path){|req, res| ...}
#   You can mount also a block by `mount_proc'.
#   This block is called when GET or POST.

#上記とは別の実装方法
s.mount_proc("/hello/again"){|req, res| 
  res.body = "<HTML>hello (again)</HTML>"
  res['Content-Type'] = "text/html"
}

trap("INT"){ s.shutdown }
s.start

すげぇ。。。簡単にできるんですね。
これはアリかも。


しっかし、シンタックスハイライトは綺麗だねー。