How to Get URL Parameters with Golang
URL parameters (aka query string parameters or URL variables) are used to send data between web pages or between a client and a server through a URL. They are composed of a key-value pair separated by an equals sign.
For example in the URL www.example.com?car=sedan&color=blue
, car
and sedan
are both parameters with values of sedan
and blue
, respectively. Note that the query string preceded with a question mark (?)
and each additional parameter is connected with an ampersand (&
).
Parameters are used to send search queries, link referrals, user preferences, and other data between pages or to a server.
In this article, we’ll show you how to parse and manipulate URL parameters using Golang.
All of the code in this article is available here in a Go Playground.
Getting a URL Parameter
In Golang, understanding how to use URL parameters is essential for building backend web applications. By using the net/http package in Golang, developers can parse URLs and their parameters to use the information to process requests and generate responses.
Assuming that our URL is a string with params like https://example.com/?product=shirt&color=blue&newuser&size=m
, we can extract the query string with url.ParseQuery
:
urlStr := "https://example.com/?product=shirt&color=blue&newuser&size=m"
myUrl, _ := url.Parse(urlStr)
params, _ := url.ParseQuery(myUrl.RawQuery)
fmt.Println(params)
// Output: map[color:[blue] newuser:[ ] product:[shirt] size:[m]]
We can then access individual query parameters using the key:
product := params.Get("product") fmt.Println(product) // Output: shirt
color := params.Get("color") fmt.Println(color) // Output: blue
newUser := params.Get("newuser") fmt.Println(newUser) // Output:
Other Useful Methods
Checking for the Presence of a Parameter
We can use Get()
method to check whether a certain parameter exists:
if _, ok := params["product"]; ok {
fmt.Println("Product parameter exists")
}
if _, ok := params["paymentmethod"]; !ok {
fmt.Println("Paymentmethod parameter does not exist")
}
Getting All of a Parameter’s Values
We can use params[key]
to return all the values associated with a particular parameter:
sizes := params["size"] fmt.Println(sizes) // Output: [m]
//Programmatically add a second size parameter. params.Add("size", "xl")
fmt.Println(params["size"]) // Output: [m xl]
Iterating over Parameters
We can use a range
loop to iterate over the parameters:
for key, value := range params {
fmt.Printf("%s: %s\n", key, value)
}
// Output: color: [blue] newuser: [ ] product: [shirt] size: [m xl]
The net/url package is part of the standard library and is available in all versions of Golang, making it widely supported.
Conclusion
In this article, we have shown you how to extract and manipulate URL parameters in Golang using the built in “net/url” package.