【问题标题】:Ruby URI ManipulationRuby URI 操作
【发布时间】:2010-08-18 20:05:54
【问题描述】:

有没有办法在 Ruby 中操作 URI 以在不使用 ?& 的情况下接受参数?

例如,我希望执行以下操作:

http://localhost:5000/service/get/ip/port

而不是

http://localhost:5000/service?ip=192.168.1.1&port=1

返回给定设备的信息。这将利用完全基于 REST 的界面。

示例代码:

hello_proc = lambda do |req,res|
  res['Content-Type'] = "text/html"
  res.body = %{
     <html><body>
      Hello. You are calling from a #{req['User-Agent']}
      <p>
      I see parameters: #{req.query.keys.join(', ')}
     </body></html>
  }
end

使用此网址:http://localhost:5000/a/b 在上面,给定 URL 的 req 输出将是:

GET /a/b HTTP/1.1

在“req”中,如何处理 URI?

提前谢谢你。

【问题讨论】:

  • 你是在使用 Rails、Rack 还是其他东西来处理 http 请求?
  • 是的,WEBrick 来处理所有传入的 http 请求。

标签: ruby rest uri


【解决方案1】:

路由就是您要寻找的。来自routing at api.rubyonrails.org的文档

路由可以生成漂亮的 URL。例如:

map.connect 'articles/:year/:month/:day',
            :controller => 'articles',
            :action     => 'find_by_date',
            :year       => /\d{4}/,
            :month      => /\d{1,2}/,
            :day        => /\d{1,2}/

稍微改变一下,你就已经为 ips 和端口设置好了。

使用上面的路由,URL“localhost:3000/articles/2005/11/06”映射到

params = {:year => '2005', :month => '11', :day => '06'}

【讨论】:

  • 这看起来很不错。我会进一步调查。谢谢!
【解决方案2】:

您应该尝试 sinatra,它是一个非常轻量级的机架顶部的 REST 重点层,您可以使用它:

get '/service/get/:ip/:port' do |ip, port|
  content_type "text/html"

  "IP: #{ip} PORT: #{port}"
end

【讨论】:

  • 那太好了,但不幸的是,我正在使用已在 Rails 上开发了相当长一段时间的服务。还是谢谢你!
猜你喜欢
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 2011-05-04
  • 1970-01-01
  • 2011-10-22
  • 2017-01-14
  • 1970-01-01
相关资源
最近更新 更多