How to URL Encode a String in Golang

To encode a URL string in Go, you can use the “QueryEscape()” function. The QueryEscape() function encodes a string to be safely placed inside a URL query string.

URL encoding, or “percent encoding”, is a mechanism for representing data in a Uniform Resource Identifier (URI).

Example

package main

import (
  "fmt"
  "net/url"
)

func main() {
  URLString := "https://askgolang.com"
  encodedStr := url.QueryEscape(URLString)
  fmt.Println(encodedStr)
}
Output
https%3A%2F%2Faskgolang.com

And we got the encoded string URL.

URL Encoding multiple Query parameters

Here is the step-by-step guide:

  1. Create a “url.Values” struct.
  2. Add the query parameters to the “url.Values” struct.
  3. Use the Encode() method of the “url.Values” struct to encode the query parameters.

Example

package main

import (
  "fmt"
  "net/url"
)

func main() {
  // Create a url.Values struct.
  values := url.Values{}

  // Add the query parameters to the url.Values struct.
  values.Add("key1", "value1")
  values.Add("key2", "value2")

  // Use the Encode() method of the url.Values struct
  encodedValues := values.Encode()

  fmt.Println(encodedValues)
}

Output

key1=value1&key2=value2

URL Encoding a Path Segment

To URL encode a path segment, use the “PathEscape()” function. The PathEscape() function escapes a string for use in a URL path. It replaces special characters in the input string with their corresponding percent-encoded values, making the string safe to use as a component in a URL path.

Example

package main

import (
  "fmt"
  "net/url"
)

func main() {
  URLString := "https://askgolang.com"
  encodedStr := url.PathEscape(URLString)
  fmt.Println(encodedStr)
}
Output
https:%2F%2Faskgolang.com

That’s it.

1 thought on “How to URL Encode a String in Golang”

  1. Your method of telling everything in this paragraph is genuinely nice,
    every one be able to without difficulty be aware of it, Thanks a lot.

Comments are closed.