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:
import "net/url"
url.QueryEscape()
function:originalString := "Hello, World!"
encodedString := url.QueryEscape(originalString)
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.