如何让http服务器处理帖子请求?

时间:2015-03-10 14:44:19

标签: ruby http post webserver

我正在尝试在ruby中编写自己的http Web服务器。现在它只能处理GET请求。我也想添加对POST请求的支持。

http服务器应该如何处理发布请求?下面是我的代码,它解析request_line以获取http动词。一旦我知道动词是一个帖子,我不知道该怎么做。

def handle_request(socket, request_line)
  STDERR.puts request_line 

  header_params = request_line.split(/\r?\n/)
  first_line = header_params.shift.split(" ")
  verb = first_line[0]
  if verb == 'GET'
    path = requested_file(request_line)
    path = File.join(path, 'index.html') if File.directory?(path)

    begin
      File.open(path, 'rb') do |resource|
        send_response(socket, '200 OK', {
            'Content-Type' => content_type(resource),
            'Content-Length' => resource.size,
            'Connection' => 'close',
          },
          resource
        )
      end
    #rescue permission denied error
    rescue Errno::EACCES
      message = "Permission denied"
      send_response(socket, '403 Forbidden', {
          'Content-Type' => 'text/plain',
          'Content-Length' => message.size,
          'Connection' => 'close'
        },
        StringIO.new(message)
      )
    #rescue no such file or directory error
    rescue Errno::ENOENT, Errno::EISDIR
      message = "The file you were looking for can not be found"
      send_response(socket, '404 Not Found', {
          'Content-Type' => 'text/plain',
          'Content-Length' => message.size,
          'Connection' => 'close'
        },
        StringIO.new(message)
      )
    end
  end

  elsif verb == 'POST'
######################################
  #NOT SURE WHAT CODE SHOULD GO HERE
######################################
 end
end

0 个答案:

没有答案