如何安全地加入相对 url 段? [英] How do I safely join relative url segments?

查看:41
本文介绍了如何安全地加入相对 url 段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种将部分 url 路径段连接在一起的强大方法.有没有快速的方法来做到这一点?

I'm trying to find a robust method of joining partial url path segments together. Is there a quick way to do this?

我尝试了以下方法:

puts URI::join('resource/', '/edit', '12?option=test')

我希望:

resource/edit/12?option=test

但我收到错误:

`merge': both URI are relative (URI::BadURIError)

我过去曾为此使用过 File.join(),但将文件库用于 url 似乎有些不对.

I have used File.join() in the past for this but something does not seem right about using the file library for urls.

推荐答案

URI 的 api 并不是很好.

URI's api is not neccearily great.

URI::join 仅在第一个开始时作为具有协议的绝对 uri 时才起作用,而后面的 URI 以正确的方式是相对的......除非我尝试这样做并且甚至无法做到这一点工作.

URI::join will work only if the first one starts out as an absolute uri with protocol, and the later ones are relative in the right ways... except I try to do that and can't even get that to work.

这至少不会出错,但为什么跳过中间组件?

This at least doesn't error, but why is it skipping the middle component?

 URI::join('http://somewhere.com/resource', './edit', '12?option=test') 

我认为 URI 可能有点糟糕.它在实例上缺少重要的 api,例如实例 #join 或相对于基本 uri 进行评估的方法,这是您所期望的.只是有点烂.

I think maybe URI just kind of sucks. It lacks significant api on instances, such as an instance #join or method to evaluate relative to a base uri, that you'd expect. It's just kinda crappy.

我认为您将不得不自己编写.或者只是使用 File.join 和其他文件路径方法,在测试了所有你能想到的边缘情况之后,以确保它符合你的要求/期望.

I think you're going to have to write it yourself. Or just use File.join and other File path methods, after testing all the edge cases you can think of to make sure it does what you want/expect.

edit 2016 年 12 月 9 日我发现 addressable gem 非常有用很好.

edit 9 Dec 2016 I figured out the addressable gem does it very nicely.

base = Addressable::URI.parse("http://example.com")
base + "foo.html"
# => #<Addressable::URI:0x3ff9964aabe4 URI:http://example.com/foo.html>

base = Addressable::URI.parse("http://example.com/path/to/file.html")
base + "relative_file.xml"
# => #<Addressable::URI:0x3ff99648bc80 URI:http://example.com/path/to/relative_file.xml>

base = Addressable::URI.parse("https://example.com/path")
base + "//newhost/somewhere.jpg"
# => #<Addressable::URI:0x3ff9960c9ebc URI:https://newhost/somewhere.jpg>

base = Addressable::URI.parse("http://example.com/path/subpath/file.html")
base + "../up-one-level.html"
=> #<Addressable::URI:0x3fe13ec5e928 URI:http://example.com/path/up-one-level.html>

这篇关于如何安全地加入相对 url 段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆