英文:
How do I encode URLs containing spaces or special characters in Go?
问题
我可以帮你翻译这段内容。以下是翻译结果:
我有一个包含空格和特殊字符的URL,就像下面的例子一样:
http://localhost:8182/graphs/graph/tp/gremlin?script=g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])
在Go语言中,如何对这样的URL进行编码?
英文:
I have a URL containing spaces and special characters, like the following example:
http://localhost:8182/graphs/graph/tp/gremlin?script=g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])
How can I encode URLs like this in Go?
答案1
得分: 8
Url编码提供在net/url
包中。你可以使用以下函数:
url.QueryEscape("g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])")
这将给你:
>g.addVertex%28%5B%27id%27%3A%270af69422+5be%27%2C%27date%27%3A%271968-01-16+00%3A00%3A00+%2B0000+UTC%27%5D%29
还可以查看url.URL和url.Values。根据你的需求,它们可以解决你的问题。
如果你只有完整的URL,你可以尝试解析它,然后重新编码破碎的查询部分,像这样:
u, err := url.Parse("http://localhost:8182/graphs/graph/tp/gremlin?script=g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])")
if err != nil {
panic(err)
}
u.RawQuery = u.Query().Encode()
fmt.Println(u)
但是要小心。如果字符串包含和号(&)或井号(#),它将不会给出你期望的结果。
英文:
Url encoding is provided in the net/url
package. You have functions such as:
url.QueryEscape("g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])")
Which gives you:
>g.addVertex%28%5B%27id%27%3A%270af69422+5be%27%2C%27date%27%3A%271968-01-16+00%3A00%3A00+%2B0000+UTC%27%5D%29
Also check out url.URL and url.Values. Depending on your needs, these will solve it for you.
If you only have the entire URL you can try to parse it and then re-encode the broken query part like this:
u, err := url.Parse("http://localhost:8182/graphs/graph/tp/gremlin?script=g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])")
if err != nil {
panic(err)
}
u.RawQuery = u.Query().Encode()
fmt.Println(u)
However, be careful. If the string contains and ampersands (&) or hashmarks (#), it will not give the result you are expecting.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论