如何在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?

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.