13
12

More than 5 years have passed since last update.

POSTされてきたHTTP Requestをひたすらに標準出力するHTTPサーバをRubyで書いた

Last updated at Posted at 2015-03-13

使いどころ

あるデータを定期的にHTTPサーバにPOSTするプログラムを作ってました。

当初、評価用HTTPサーバスタブは適当にApache等が動いている仮想マシンを使っていました。
ですがPOSTされてるリクエストの中身をリアルタイムに確認したかったので、そういうものを作りました。

使い方

rubyコマンドで実行します。

$ ruby httpserver.rb

これで試しにブラウザやcurlコマンド等で http://localhost:8080 にアクセスし、 httpserver.rb を実行したコンソール上に何やら出れば成功です。

hgw.gif

終了するには Ctrl-c で。

ソース

httpserver.rb
require 'socket'

# 初期設定
port = 8080
server = TCPServer.open(port)
length = 0

# ソケット通信
loop do
  socket = server.accept

  # HTTPメッセージを1行ずつ読み出す
  while buffer = socket.gets
    puts buffer

    # Content-Lengthの値をlengthに格納
    if buffer.include? "Content-Length"
      length = buffer.split[1].to_i
    end

    # 改行のみ→次の行以降はBody
    if buffer == "\r\n"
      # BodyからContent-Length文字読み出す
      length.times do
        putc socket.getc
      end
      break
    end

  end

  puts "\n\n"

  # 無条件に200OKを返しているので必要あれば変更する
  socket.puts "HTTP/1.1 200 OK"
  socket.close
end

server.close
13
12
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
13
12