编码/解码 URL [英] Encode / decode URLs
问题描述
在 Go 中编码和解码整个 URL 的推荐方式是什么?我知道 url.QueryEscape
和 url.QueryUnescape
方法,但它们似乎并不是我正在寻找的.具体来说,我正在寻找像 JavaScript 的 encodeURIComponent
和 decodeURIComponent
之类的方法.
What's the recommended way of encoding and decoding entire URLs in Go? I am aware of the methods url.QueryEscape
and url.QueryUnescape
, but they don't seem to be exactly what I am looking for. Specifically I am looking for methods like JavaScript's encodeURIComponent
and decodeURIComponent
.
谢谢.
推荐答案
您可以使用 net/url 模块.它不会为 URL 的各个部分分解单独的编码函数,您必须让它构建整个 URL.仔细观察源代码后,我认为它做得非常好且符合标准.
You can do all the URL encoding you want with the net/url module. It doesn't break out the individual encoding functions for the parts of the URL, you have to let it construct the whole URL. Having had a squint at the source code I think it does a very good and standards compliant job.
这是一个例子(playground 链接)
package main
import (
"fmt"
"net/url"
)
func main() {
Url, err := url.Parse("http://www.example.com")
if err != nil {
panic("boom")
}
Url.Path += "/some/path/or/other_with_funny_characters?_or_not/"
parameters := url.Values{}
parameters.Add("hello", "42")
parameters.Add("hello", "54")
parameters.Add("vegetable", "potato")
Url.RawQuery = parameters.Encode()
fmt.Printf("Encoded URL is %q
", Url.String())
}
打印什么
Encoded URL is "http://www.example.com/some/path/or/other_with_funny_characters%3F_or_not/?vegetable=potato&hello=42&hello=54"
这篇关于编码/解码 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!