Package net/url

Package net/url

Go offers us the package net/url to make URLs manipulation easier, with it, we can build, analyze and manipulate URLs.

Extracting properties from a URL

In the example below we’ll extract the properties scheme, host, path and query parameter.

	u, err := url.Parse("https://www.google.com/search?q=golang")
	if err != nil {
		panic(err)
	}

	fmt.Printf("Scheme: %s\n", u.Scheme)
	fmt.Printf("Host: %s\n", u.Host)
	fmt.Printf("Path: %s\n", u.Path)
	fmt.Printf("RawQuery: %s\n", u.RawQuery)
>> Scheme: https
>> Host: www.google.com
>> Path: /search
>> RawQuery: q=golang

Building and manipulating parameters

In order to create parameters with the package net/url we can use the function Add from type Values as we can see in the example below.

	queryParameters := url.Values{}
	queryParameters.Add("app_name", "movie_service")
	queryParameters.Add("database", "movies")

	fmt.Println(queryParameters.Encode())
>> app_name=movie_service&database=movies

Adding more than one value in the same parameter

	queryParameters := url.Values{}
	queryParameters.Add("type", "frame")
	queryParameters.Add("colors", "blue")
	queryParameters.Add("colors", "green")
	queryParameters.Add("colors", "yellow")

	fmt.Println(queryParameters.Encode())
>> colors=blue&colors=green&colors=yellow&type=frame

Altering a parameters value

In order to alter a parameter value we can use the function Set, as we can see in the example below.

	queryParameters := url.Values{}
	queryParameters.Add("app_name", "movie_service")
	queryParameters.Add("database", "movies")

	fmt.Println(queryParameters.Encode())

	queryParameters.Set("database", "theater")

	fmt.Println(queryParameters.Encode())
>> app_name=movie_service&database=movies
>> app_name=movie_service&database=theater

Getting the value from just one parameter

We can get the value from a parameter through the Get function.

	queryParameters := url.Values{}
	queryParameters.Add("app_name", "movie_service")
	queryParameters.Add("database", "movies")

	d := queryParameters.Get("database")
	fmt.Println(d)
>> movies

Checking if the parameter exists

We can check the existence of a parameter through the Has function.

	queryParameters := url.Values{}
	queryParameters.Add("app_name", "movie_service")
	queryParameters.Add("database", "movies")

	d := queryParameters.Has("database")
	fmt.Println(d)
>> true

Removing a parameter

We can remove a parameter through the Del function.

Tip

If the parameter doesn’t exist, no error will be throwed.

	queryParameters := url.Values{}
	queryParameters.Add("app_name", "movie_service")
	queryParameters.Add("database", "movies")

	queryParameters.Del("database")
	fmt.Println(queryParameters.Encode())
>> app_name=movie_service