How to URL Encode a String in Golang

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

URL Encoding a Query String in Go

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.

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 in Go

Here are the steps on how to URL encode multiple query parameters in Go:

  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 in Go

To URL encode a path segment in Go, you can use the “PathEscape()” function. The PathEscape() function escapes a string for use in a URL path.

The PathEscape() function 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.

Leave a Comment