LoginSignup
45
34

More than 5 years have passed since last update.

webrickでサーバー作った

Posted at

今回遊びでwebrickでwebサーバーを作ったので。

webrick?

Rubyに標準添付されているサーバー用のフレームワーク。
ちょこっとコードを書くだけでサーバーが作れる。

webrick.rb
require 'webrick'

srv = WEBrick::HTTPServer.new({
  DocumentRoot:   './',
  BindAddress:    IPアドレス,
  Port:           ポート,
})

srv.start

で、実行。
以下のような待ち状態になればOK

[vagrant:ruby] $ ruby webrick.rb
[2016-02-14 21:59:58] INFO  WEBrick 1.3.1
[2016-02-14 21:59:58] INFO  ruby 2.3.0 (2015-12-25) [x86_64-linux]
[2016-02-14 21:59:58] INFO  WEBrick::HTTPServer#start: pid=17156 port=20000

そしてブラウザなり他のウィンドウからリクエストを送って動作確認。

これだけで一応動いてしまう。

htmlを返す

ルートパスにきたら、htmlファイルを返すようにする。
webrickが動いているコードと同じディレクトリに

index.html
<html>
    <head></head>
    <body>
        <h1>テスト</h1>
    </body>
</html>

そして、webrick.rbに以下を追加。

webrick.rb
srv.mount('/', WEBrick::HTTPServlet::FileHandler, 'index.html')

ブラウザアクセスでテストが表示されたらok

こんな書き方もできる。

webrick.rb
srv.mount_proc '/' do |req, res|
  File.open("index.html") do |f|
    res.body = f.read
  end
end

パラメータを処理する

次はパラメータを受け取ってみましょう。

先ほどのコードを少しいじります。

srv.mount_proc '/' do |req, res|
  res.body = req.query['a']
end

そして、ipアドレス:ポート/?a=hoge
にアクセスしてhogeが表示されたら完了

CGIHandlerを使う

以下のコードをwebrick.rbに追加

webrick.rb
srv.mount('/cgi', WEBrick::HTTPServlet::CGIHandler, './cgi.rb')

同じディレクトリにcgi.rbを用意

cgi.rb
require 'cgi'

cgi = CGI.new
cgi.out(type: 'text/html',
        charset: 'UTF-8') do
  get = cgi['a']
  "<html><body><p>#{get}</p></body></html>"
end

ipアドレス:ポート/cgi?a=hoge
にアクセス。

45
34
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
45
34