The way to Get URL Parameters with Golang — SitePoint | Digital Noch

URL parameters (aka question string parameters or URL variables) are used to ship knowledge between net pages or between a shopper and a server by means of a URL. They’re composed of a key-value pair separated by an equals signal.

For instance within the url: www.instance.com?automotive=sedan&shade=blue, automotive and sedan are each parameters with values of sedan and blue , respectively. Word that the question string preceded with a query mark (?) and every extra parameter is related with an ampersand (&).

Parameters are used to ship search queries, hyperlink referrals, consumer preferences, and different knowledge between pages or to a server.

On this article, we’ll present you tips on how to parse and manipulate URL parameters utilizing Golang.

The entire code on this article is accessible right here in a Go Playground.

Getting a URL Parameter

In Golang, understanding tips on how to use URL parameters is important for constructing backend net purposes. Through the use of the web/http bundle in Golang, builders can parse URLs and their parameters to make use of the data to course of requests and generate responses.

Assuming that our URL is a string with params like: https://instance.com/?product=shirt&shade=blue&newuser&dimension=m, we are able to extract the question string with url.ParseQuery:

urlStr := "
myUrl, _ := url.Parse(urlStr)
params, _ := url.ParseQuery(myUrl.RawQuery)
fmt.Println(params)

We will then entry particular person question parameters utilizing the important thing:

product := params.Get("product") fmt.Println(product) 

shade := params.Get("shade") fmt.Println(shade) 

newUser := params.Get("newuser") fmt.Println(newUser) 

Different Helpful Strategies

Checking for the Presence of a Parameter

We will use Get() technique to verify whether or not a sure parameter exists:

if _, okay := params["product"]; okay { 
    fmt.Println("Product parameter exists")
}

if _, okay := params["paymentmethod"]; !okay {
    fmt.Println("Paymentmethod parameter doesn't exist")
}

Getting All of a Parameter’s Values

We will use params[key] to return all of the values related to a selected parameter:

sizes := params["size"] fmt.Println(sizes) 



fmt.Println(params["size"]) 

Iterating over Parameters

We will use a vary loop to iterate over the parameters:

for key, worth := vary params {
    fmt.Printf("%s: %sn", key, worth)
}

The web/url bundle is a part of the usual library and is offered in all variations of Golang, making it broadly supported.

Conclusion

On this article, we have now proven you tips on how to extract and manipulate URL parameters in Golang utilizing the inbuilt “web/url” bundle.

Related articles

spot_img

Leave a reply

Please enter your comment!
Please enter your name here