LoginSignup
0
0

More than 5 years have passed since last update.

Ruby の WEBrick で簡単 HTTP サーバ

Last updated at Posted at 2014-02-22

Ruby の標準ライブラリ webrick で簡単に HTTP サーバが作れます。

server.rb
#!/usr/bin/env ruby

require 'webrick'
require 'optparse'

params = { 
  :DocumentRoot => '.',
  :BindAddress => '0.0.0.0',
  :Port => 4000
}

opt = OptionParser.new
opt.on('-d docroot') { |v| params[:DocumentRoot] = v } 
opt.on('-o address') { |v| params[:BindAddress] = v }
opt.on('-p port') { |v| params[:Port] = v.to_i }
begin
  opt.parse(ARGV)
rescue => e
  puts e
  exit 1
end

srv = WEBrick::HTTPServer.new(params)

trap("INT") do
  srv.shutdown
end

srv.start

使い方

$ ./server.rb --help
Usage: server [options]
    -d docroot
    -o address
    -p port
$ ./server.rb -d /path/to/docroot -o 0.0.0.0 -p 4000

任意のディレクトリ内のファイルを HTTP サーバで公開できます。

Ruby-1.9.3

Ruby-1.9.3 の場合、WEBrick のログに以下のような警告が出る場合があります。

WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

以下のバグ報告チケットにあるとおり、Keep-Alive 接続時に HTTPステータスコード が 204/304 の場合に発生します。

同チケットに添付されている 204_304_keep_alive.patch のパッチを当てて解決します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0