2

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 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

someaddress.com/… 00:00:00 +0000 UTC','full_birth_time':'1968-01-16 03:33:00 +0000 UTC']) to someaddress.com/…
@PriyadarshiniRavi I've updated the answer with an example of parsing. But as I've mentioned: this can cause trouble as characters like & and # serves other functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.