In Go, you can use the url
package to encode and decode URL parameters and query strings. Here's an example of how to do it:
url
package:import (
"net/url"
)
func encodeURLParams() {
params := url.Values{}
params.Set("key1", "value1")
params.Set("key2", "value2")
encodedParams := params.Encode()
fmt.Println(encodedParams) // Output: "key1=value1&key2=value2"
}
func encodeQueryParam() {
baseURL := "https://example.com"
params := url.Values{}
params.Set("key1", "value1")
params.Set("key2", "value2")
// Encode the parameters
encodedParams := params.Encode()
// Append the encoded parameters to the URL
encodedURL := baseURL + "?" + encodedParams
fmt.Println(encodedURL) // Output: "https://example.com?key1=value1&key2=value2"
}
func decodeURLParams() {
query := "key1=value1&key2=value2"
// Parse the query string
params, err := url.ParseQuery(query)
if err != nil {
fmt.Println("Error parsing query:", err)
return
}
// Access the values by key
value1 := params.Get("key1")
value2 := params.Get("key2")
fmt.Println(value1) // Output: "value1"
fmt.Println(value2) // Output: "value2"
}
Note: Remember to handle errors appropriately while parsing or encoding the URL parameters.