将PUT / DELETE添加到Ruby WEBrick

时间:2014-05-30 05:53:38

标签: ruby webrick

我试图将PUT和DELETE动词添加到WEBrick。我不需要他们做任何事情。他们只需要用200响应。下面是我正在运行的脚本。 GET有效,但是DELETE返回405,其中包含"不支持的方法DELETE"信息。任何人都可以告诉我这段代码有什么问题或缺失吗?

require 'webrick'

module WEBrick
  module HTTPServlet
    class ProcHandler
      alias do_PUT    do_GET
      alias do_DELETE do_GET
    end
  end
end

sRoot = "C:\\"

server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => sRoot

trap "INT" do server.shutdown end

server.start

3 个答案:

答案 0 :(得分:2)

我明白了。我必须向DefaultFileHandler添加适当的处理程序。 @kimmo,谢谢你的提示!

require 'webrick'

module WEBrick
  module HTTPServlet
    class FileHandler
      alias do_PUT    do_GET
      alias do_DELETE do_GET
    end

    class DefaultFileHandler
      def do_DELETE(req, res)
        res.body = ''
      end

      def do_PUT(req, res)
        res.body = ''
      end
    end
  end
end

sRoot = "C:\\"

server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => sRoot

trap "INT" do server.shutdown end

server.start

答案 1 :(得分:2)

查看Rack's WEBrick implementation也提供了丰富的信息。

Rack会覆盖WEBrick::HTTPServlet::AbstractServlet#service method

一个例子:

require 'webrick'

class TestServer < WEBrick::HTTPServlet::AbstractServlet
  def service(request, response)
    response.body = "#{request.request_method}:\n\t" +
      "#{request.inspect.lines.to_a.join("\t")}"
  end
end

server = WEBrick::HTTPServer.new Port: 8000
server.mount '/', TestServer
trap 'INT' do server.shutdown end
server.start

curl -X DELETE localhost:8000

给出

DELETE:
  DELETE / HTTP/1.1
  User-Agent: curl/7.35.0
  Host: localhost:8000
  Accept: */*

答案 2 :(得分:1)

肯特的回答对我不起作用......也许WEBrick已经更新......

但它确实给了我线索。

  module HTTPServlet
    class ProcHandler
      alias do_PUT    do_GET
      alias do_DELETE do_GET
    end
  end

  @server = WEBrick::HTTPServer.new( config )
  @server.mount_proc '/' do | req, res |
    ...
  end

  @server.start

ruby​​ 2.2.3p173