11

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?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
  • 5
    Use [url.QueryEscape](https://godoc.org/net/url#QueryEscape) ([example](https://play.golang.org/p/84x4WVMlzaU)). – Charlie Tumahai Oct 16 '19 at 18:14
  • 1
    FTR: Go supports repeated query parameters just fine (url.Values is a `map[string][]string` for this reason): https://play.golang.org/p/ykpj0wn9CcI. I have never seen the order of parameters matter, but yes, Go won't necessarily preserve them if you parse the URL (also due to using a map). – Peter Oct 16 '19 at 18:24

1 Answers1

21

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))
}
Francesco Casula
  • 26,184
  • 15
  • 132
  • 131
Francisco Arias
  • 582
  • 7
  • 15