How to Get URL Parameters with Golang

Share this article

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.

FAQs on URL Parsing and Manipulation in Go Programming

How can I parse a URL in Go?

Parsing a URL in Go is a straightforward process. You can use the url.Parse function from the net/url package. This function takes a string URL as an argument and returns a parsed URL if successful. Here’s an example:

package main

import (
"fmt"
"net/url"
)

func main() {
u, err := url.Parse("http://example.com?key=value")
if err != nil {
panic(err)
}
fmt.Println(u)
}
In this code, url.Parse is used to parse the URL string. If the parsing is successful, the parsed URL is printed to the console.

How can I extract query parameters from a URL in Go?

To extract query parameters from a URL in Go, you can use the Query method of the URL type. This method returns a Values type, which is a map of string slices. Here’s an example:

package main

import (
"fmt"
"net/url"
)

func main() {
u, _ := url.Parse("http://example.com?key=value")
q := u.Query()
fmt.Println(q.Get("key"))
}
In this code, u.Query() is used to get the query parameters from the URL. The Get method of the Values type is then used to get the value of the “key” parameter.

How can I modify query parameters in a URL in Go?

Modifying query parameters in a URL in Go can be done using the Set method of the Values type. This method sets the value of a query parameter. Here’s an example:

package main

import (
"fmt"
"net/url"
)

func main() {
u, _ := url.Parse("http://example.com?key=value")
q := u.Query()
q.Set("key", "newvalue")
u.RawQuery = q.Encode()
fmt.Println(u)
}
In this code, q.Set("key", "newvalue") is used to set the value of the “key” parameter to “newvalue”. The Encode method of the Values type is then used to encode the query parameters back into a string, which is set as the new raw query of the URL.

How can I remove a query parameter from a URL in Go?

To remove a query parameter from a URL in Go, you can use the Del method of the Values type. This method deletes the values associated with a key. Here’s an example:

package main

import (
"fmt"
"net/url"
)

func main() {
u, _ := url.Parse("http://example.com?key=value")
q := u.Query()
q.Del("key")
u.RawQuery = q.Encode()
fmt.Println(u)
}
In this code, q.Del("key") is used to delete the “key” parameter from the query parameters. The Encode method of the Values type is then used to encode the query parameters back into a string, which is set as the new raw query of the URL.

How can I add a query parameter to a URL in Go?

Adding a query parameter to a URL in Go can be done using the Add method of the Values type. This method adds a value to a key. Here’s an example:

package main

import (
"fmt"
"net/url"
)

func main() {
u, _ := url.Parse("http://example.com")
q := u.Query()
q.Add("key", "value")
u.RawQuery = q.Encode()
fmt.Println(u)
}
In this code, q.Add("key", "value") is used to add the “key” parameter with the value “value” to the query parameters. The Encode method of the Values type is then used to encode the query parameters back into a string, which is set as the new raw query of the URL.

Mark O'NeillMark O'Neill
View Author

Mark is the General Manager of SitePoint.com. He loves to read and write about technology, startups, programming languages, and no code tools.

gogolang
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week