Many languages, such as JavaScript and PHP, have a urlencode()
function which one can use to encode the content of a query string parameter.
"example.com?value=" + urlencode("weird string & number: 123")
This ensures that the &
, %
, spaces, etc. get encoded so your URL remains valid.
I see that golang offers a URL package and it has an Encode() function for query string values. This works great, but in my situation, it would require me to parse the URL and I would prefer to not do that.
My URLs are declared by the client and not changing the order and potential duplicated parameters (which is a legal thing in a URL) could be affected. So I use a Replace()
like so:
func tweak(url string) string {
url.Replace("@VALUE@", new_value, -1)
return url
}
The @VALUE@
is expected to be used as the value of a query string parameter as in:
example.com?username=@VALUE@
So, what I'd like to do is this:
url.Replace("@VALUE@", urlencode(new_value), -1)
Is there such a function readily accessible in Golang?
In Golang we have 2 basic functions in net/url package for encoding different parts of the URL: url.QueryEscape () to encode string that is placed inside an URL query.
URL Encoded data is also referred to as application/x-www-form-urlencoded MIME format. Go’s net/url package contains a built-in method called QueryEscape to escape/encode a string so that it can be safely placed inside a URL query.
URL Decoding is the inverse operation of URL encoding. It converts the encoded characters back to their normal form. Go’s net/url package contains a built-in method called QueryUnescape to unescape/decode a string. The following example shows how to decode a query string in Golang -
URLENCODE is a string manipulation function that manipulates CHARACTER string data. URLENCODE returns a CHARACTER string that contains the source string in which the characters are not interpreted as special characters within a URL. RFC3986 encoding is used by default.
Yeah you can do it with functions like these ones here:
package main
import (
"encoding/base64"
"fmt"
"net/url"
)
func main() {
s := "enc*de Me Plea$e"
fmt.Println(EncodeParam(s))
fmt.Println(EncodeStringBase64(s))
}
func EncodeParam(s string) string {
return url.QueryEscape(s)
}
func EncodeStringBase64(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With