12
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Ruby 標準ライブラリの WEBrick で Web サーバを作る

発端

Web ブラウザからどういう内容が送信されているかを見るために書いてみた。

WEBrick を使った Web サーバのサンプルコード

このコードを実行すると、 Web サーバが起動する。

require 'webrick'
require 'cgi'

s = WEBrick::HTTPServer.new(
  :Port => 8000,
  :HTTPVersion => WEBrick::HTTPVersion.new('1.1'),
  :AccessLog => [[open(IO::NULL, 'w'), '']] # アクセスログを出力しない
)

s.mount_proc('/') do |req, res|
  puts "========== #{Time.new} =========="
  # リクエスト内容を出力
  puts req.request_line
  puts ''
  puts req.raw_header
  puts "\n#{req.body}" if req.body
  # レスポンス内容を出力
  body = "<html><body>\n"
  body += "#{CGI.escapeHTML(req.request_line)}"
  body += "<br>#{CGI.escapeHTML(req.body)}\n" if req.body
  body += "</body></html>\n"
  res.status = 200
  res['Content-Type'] = 'text/html'
  res.body = body
end

Signal.trap('INT'){s.shutdown}
s.start

curl コマンドでサンプルの Web サーバに HTTP GET アクセスしてみる

curl コマンドの実行結果。

$ curl -sSv 'http://localhost:8000/a/b/?c=d'
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8000 (#0)
> GET /a/b/?c=d HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html
< Server: WEBrick/1.3.1 (Ruby/2.4.1/2017-03-22)
< Date: Thu, 27 Apr 2017 13:43:25 GMT
< Content-Length: 52
< Connection: Keep-Alive
<
<html><body>
GET /a/b/?c=d HTTP/1.1
</body></html>
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact

Web サーバ側の出力結果。

========== 2017-04-27 22:43:25 +0900 ==========
GET /a/b/?c=d HTTP/1.1

Host: localhost:8000
User-Agent: curl/7.51.0
Accept: */*

curl コマンドでサンプルの Web サーバに HTTP POST アクセスしてみる

curl コマンドの実行結果。

$ curl -sSv -X POST 'http://localhost:8000/a/b/?c=d' --data 'e=f'
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8000 (#0)
> POST /a/b/?c=d HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.51.0
> Accept: */*
> Content-Length: 3
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 3 out of 3 bytes
< HTTP/1.1 200 OK
< Content-Type: text/html
< Server: WEBrick/1.3.1 (Ruby/2.4.1/2017-03-22)
< Date: Thu, 27 Apr 2017 13:43:37 GMT
< Content-Length: 61
< Connection: Keep-Alive
<
<html><body>
POST /a/b/?c=d HTTP/1.1
<br>e=f
</body></html>
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact

Web サーバ側の出力結果。

========== 2017-04-27 22:43:37 +0900 ==========
POST /a/b/?c=d HTTP/1.1

Host: localhost:8000
User-Agent: curl/7.51.0
Accept: */*
Content-Length: 3
Content-Type: application/x-www-form-urlencoded

e=f

参考資料

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
12
Help us understand the problem. What are the problem?