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?
1 Answer
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))
}