gpt4 book ai didi

ruby - URI.escape 和 CGI​​.escape 有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 06:17:11 34 4
gpt4 key购买 nike

URI.escapeCGI.escape 有什么区别,我应该使用哪一个?

最佳答案

斧头和剑有什么区别,我应该使用哪一种?好吧,这取决于您需要做什么。

URI.escape 应该将字符串 (URL) 编码为所谓的“Percent-encoding ”。

CGI::escape 来自 CGI规范,它描述了数据应该如何在网络服务器和应用程序之间编码/解码。

现在,假设您需要在应用中转义 URI。这是一个更具体的用例。为此,Ruby 社区多年来一直使用 URI.escapeURI.escape 的问题在于它无法处理 RFC-3896 规范。

URI.escape 'http://google.com/foo?bar=at#anchor&title=My Blog & Your Blog' 
# => "http://google.com/foo?bar=at%23anchor&title=My%20Blog%20&%20Your%20Blog"

URI.escape 被标记为过时:

Moreover current URI.encode is simple gsub. But I think it should split a URI to components, then escape each components, and finally join them.

So current URI.encode is considered harmful and deprecated. This will be removed or change behavior drastically.

What is the replacement at this time?

正如我上面所说,当前的 URI.encode 在规范级别上是错误的。所以我们 不会提供确切的替代品。更换将因它而异 用例。

https://bugs.ruby-lang.org/issues/4167

不幸的是,文档中只字未提,了解它的唯一方法是检查源代码,或者运行带有详细级别警告的脚本 (-wW2) (或者使用一些 google-fu)。

一些 proposed使用 CGI::Escape 作为查询参数,因为您无法转义整个 URI:

CGI::escape 'http://google.com/foo?bar=at#anchor&title=My Blog & Your Blog'
# => "http%3A%2F%2Fgoogle.com%2Ffoo%3Fbar%3Dat%23anchor%26title%3DMy+Blog+%26+Your+Blog"

CGI::escape 应该只用于查询参数,但结果将再次违反规范。实际上,最常见的用例是转义表单数据,例如在发送 application/x-www-form-urlencoded POST 请求时。

还提到 WEBrick::HTTPUtils.escape 没有太大改进(同样它只是一个简单的 gsub,在我看来,它甚至比 URI.escape):

WEBrick::HTTPUtils.escape 'http://google.com/foo?bar=at#anchor&title=My Blog & Your Blog'
# => "http://google.com/foo?bar=at%23anchor&title=My%20Blog%20&%20Your%20Blog"

最接近规范的似乎是 Addressable gem :

require 'addressable/uri'
Addressable::URI.escape 'http://google.com/foo?bar=at#anchor&title=My Blog & Your Blog'
# => "http://google.com/foo?bar=at#anchor&title=My%20Blog%20&%20Your%20Blog"

请注意,与之前的所有选项不同,Addressable 不会转义 #,这是预期的行为。您希望将 # 散列保留在 URI 路径中,但不保留在 URI 查询中。

剩下的唯一问题是我们没有正确地转义我们的查询参数,这使我们得出结论:我们不应该对整个 URI 使用单一方法,因为没有完美的解决方案(到目前为止)。如您所见,& 并未从“我的博客和您的博客”中转义。我们需要对查询参数使用不同形式的转义,用户可以在 URL 中放置具有特殊含义的不同字符。输入 URL 编码。 URL 编码应该用于每个“可疑”的查询值,类似于 ERB::Util.url_encode 所做的:

ERB::Util.url_encode "My Blod & Your Blog"
# => "My%20Blod%20%26%20Your%20Blog""

这很酷,但我们已经需要 Addressable:

uri = Addressable::URI.parse("http://www.go.com/foo")
# => #<Addressable::URI:0x186feb0 URI:http://www.go.com/foo>
uri.query_values = {title: "My Blog & Your Blog"}
uri.normalize.to_s
# => "http://www.go.com/foo?title=My%20Blog%20%26%20Your%20Blog"

结论:

  • 不要使用 URI.escape 或类似的
  • 如果您只需要表单转义,请使用CGI::escape
  • 如果您需要使用 URI,请使用 Addressable,它提供 URL 编码、表单编码和规范化 URL。
  • 如果是Rails项目,查看“How do I URL-escape a string in Rails?

关于ruby - URI.escape 和 CGI​​.escape 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2824126/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com