How to handle special characters and escaping in URL encoding and decoding in Go?

In Go, you can handle special characters and escaping in URL encoding and decoding using the "net/url" package. This package provides functions to escape and unescape special characters in URLs.

Here's an example of how you can URL encode and decode a string in Go:

  1. Import the "net/url" package:
import "net/url"
  1. URL encode a string using the url.QueryEscape() function:
originalString := "Hello, World!" encodedString := url.QueryEscape(originalString)
  1. URL decode the encoded string using the url.QueryUnescape() function:
decodedString, err := url.QueryUnescape(encodedString) if err != nil { // Handle error }

Make sure to check for errors when decoding the URL, as it may return an error if the string is not valid.

Here's a complete example:

package main import ( "fmt" "net/url" ) func main() { originalString := "Hello, World!" encodedString := url.QueryEscape(originalString) fmt.Println("Encoded: ", encodedString) decodedString, err := url.QueryUnescape(encodedString) if err != nil { fmt.Println("Error decoding URL: ", err) return } fmt.Println("Decoded: ", decodedString) }

This will output:

Encoded: Hello%2C+World%21 Decoded: Hello, World!

Note that url.QueryEscape() encodes spaces as + instead of %20, which is the standard encoding for spaces in URLs. However, url.QueryUnescape() is smart enough to handle this and decode + back to spaces.

Additionally, you can also use url.PathEscape() and url.PathUnescape() to only encode or decode the path component of a URL, which follows a slightly different encoding/decoding standard than the query component.