8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WEBrickでサーバを起動する

Last updated at Posted at 2015-05-10

ワンライナーといかないまでも、1ファイルでそれなりに動くWebサーバが欲しかったのでRubyの標準ライブラリのWEBrickで書いた。

後述のコードを~/bin/webrickあたりにコピーして実行権限を付けて起動する。要ruby。1.8系でも動く。

起動オプションとしては

  • -dでデーモンとして起動する
    • 停止するときはpsとかからプロセスを調べてkillする
  • -pでポート番号を指定する。デフォルトは8000
  • -rでルートディレクトリを指定する。デフォルトはカレントディレクトリ
  • -lでアクセスログを出力するようになる。デフォルトはカレントディレクトリ直下のaccess.log
webrick
# !/usr/bin/env ruby
#
# -*- mode: ruby -*-
# vi: set ft=ruby :
 
require "optparse"
require "webrick"
include WEBrick
 
Process.setproctitle(File.basename(__FILE__)) if Process.respond_to?(:setproctitle)
 
options = {
  :Port => 8000,
  :DocumentRoot => Dir.pwd,
  :BindAddress => "0.0.0.0",
}
 
OptionParser.new do |opt|
  opt.on "-d", "--[no-]daemon" do |v|
    options[:ServerType] = Daemon if v
  end
 
  opt.on "-p", "--port PORT", Integer do |v|
    options[:Port] = v
  end
 
  opt.on "-r", "--root PATH" do |v|
    options[:DocumentRoot] = v
  end
 
  opt.on "-l", "--log [PATH]" do |v|
    v ||= "access.log"
    path = File.expand_path(v, Dir.pwd)
    f = File.open(path, "a")
    f.sync = true
    options[:AccessLog] = [
      [f, WEBrick::AccessLog::COMBINED_LOG_FORMAT]
    ]
  end
end.parse!(ARGV)
 
server = HTTPServer.new(options)
 
%w(INT TERM).each do |sig|
  trap(sig) { server.shutdown }
end
 
server.start
8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?