如何在路线中使用Sinatra URL作为参数?

bla*_*014 3 ruby routes sinatra

我正在使用Sinatra路由,如果可能的话,我想解释一个普通的HTTP地址作为路由中的参数:

url http://somesite/blog/archives   
Run Code Online (Sandbox Code Playgroud)

路线是:

/http://somesite/blog/archives 
Run Code Online (Sandbox Code Playgroud)

代码是:

get '/:url' do |u|  
(some code dealing with url)
Run Code Online (Sandbox Code Playgroud)

HTTP URL中的各种"/"正在产生问题.

我找到的解决方法是仅传递上面示例中"somesite"所代表的URL部分,然后使用:

get '/:url' do |u|
buildUrl = "http://#{u}/blog/archives"
(some code dealing with url)
Run Code Online (Sandbox Code Playgroud)

有没有办法直接处理完整的URL?

Ale*_*eue 6

这不会像您指定的那样工作.正如您所注意到的那样,斜线会带来麻烦.你可以做的是将URL作为查询字符串参数传递而不是URL的一部分.

get '/example' do
  url = params[:url]
  # do code with url
end
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过发送数据来抓取您想要的任何内容 http://yoursite.com/example?url=http://example.com/blog/archives