Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode / decode URLs

Tags:

url

escaping

go

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.

Thanks.

like image 702
Sergi Mansilla Avatar asked Dec 11 '12 12:12

Sergi Mansilla


People also ask

How do I decode a URL link?

Wikipedia has a good expalanation of how some characters should be represented in URLs and URIs. Load the URL data to decode from a file, then press the 'Decode' button: Browse: Alternatively, type or paste in the text you want to URL–decode, then press the 'Decode' button.

How do I encode text in URL?

Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is %2f in URL?

URL encoding converts characters into a format that can be transmitted over the Internet. - w3Schools. So, "/" is actually a seperator, but "%2f" becomes an ordinary character that simply represents "/" character in element of your url.


1 Answers

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.

Here is an example (playground link)

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\n", Url.String()) } 

Which prints

Encoded URL is "http://www.example.com/some/path/or/other_with_funny_characters%3F_or_not/?vegetable=potato&hello=42&hello=54" 
like image 96
Nick Craig-Wood Avatar answered Sep 24 '22 22:09

Nick Craig-Wood