1

我知道几个可以发出 http 请求的宝石,例如 net 或 faraday。但是在 ruby​​ 程序中有什么东西可以接收 Http 请求吗?谢谢

4

1 回答 1

1

要接收 HTTP 请求,您需要一种在某个端口(HTTP 服务器)上侦听 HTTP 请求的方法。

您可以自己编写,或者从许多已经可用的中选择一个,或者您可以使用Ruby 标准库中包含的WEBrick 。

为了给你一个想法,这里是一个使用 WEBrick 的简单示例:

require 'webrick'

server = WEBrick::HTTPServer.new(:Port => 8000)

class MyServlet < WEBrick::HTTPServlet::AbstractServlet
  def do_GET(request, response)
    response.body = "You requested '#{request.path}'"
  end
end

server.mount('', MyServlet)
trap('INT') {server.shutdown} # so you can stop the server using Ctrl-C
server.start

然后你可以提出一些要求:

curl localhost:8000           # => You requested '/'
curl localhost:8000/something # => You requested '/something'
于 2013-10-01T19:19:16.547 回答