golang

Golang Net/URL Examples

To work with URLs, the Go language’s net/url package provides a wide range of functions. URLs play a crucial role in web development as they are used to identify and locate the resources on the internet. The net/url package in Go provides a robust set of tools to parse, manipulate, and construct the URLs. In this article, we will go into the Go language’s net/url package and examine all of its operations.

Example 1: Using the Golang Net/URL Package to Parse the URL

The net/url package in Go provides functionality to parse and manipulate the URLs using the url.Parse() function. Consider the program of parsing the URL with the net/url package.

package main
import (
   "fmt"
   "net/url"
)
func main() {
   u1, e1 := url.ParseRequestURI("https://linuxhint.com/")
   if e1 != nil {
      panic(e1)
   }
   fmt.Println(u1)
}

Here, we import the net/url package to work with the URLs. We then define the main() function where the url.ParseRequestURI() function is used to parse the specified URL string. This function takes a URL string as input and returns a parsed *url.URL structure and an error. In this case, the parsed URL is assigned to the “u1” variable and any error that occurs during parsing is assigned to the “e1” variable. After that, we check if the “e1” error value is not nil (i.e., if an error occurrs during parsing). If an error occurs, the panic(e1) is deployed there which terminates the program.

The URL is parsed by the url.ParseRequestURI() function of the net/url package in the following output:

Example 2: Using the Golang Net/URL Package to Encode the URL Values

Moreover, Go also provides the functionality to encode the URL values which can be accomplished using the Encode() function. Here’s the program where the Encode() method is called to encode the provided URL:

package main
import (
  "fmt"
  "net/url"
)
func main() {
  MyValues := url.Values{}
  MyValues.Add("k1", "val1")
  MyValues.Add("k2", "val2")
  EncodedValues := MyValues.Encode()
  fmt.Println(EncodedValues)
}

After importing the necessary package in the import section, we move toward the main() function. Here, the main() function initializes an empty URL. The “Values” object is called “MyValues”. This object is used to store the key-value pairs that are encoded into a URL query string.

Next, we add two key-value pairs to “MyValues” using the Add() method. The key-value pairs are “k1” with the “val1” value and “k2” with the “val2” value. Then, we encode the key-value pairs into a URL query string using the Encode() method that is called on “MyValues” to convert the key-value pairs into a URL-encoded string. That encoded string is then stored in the “EncodedValues” variable.

The following output showcases the URL-encoded string representation of the key-value pairs on the Go console:

Example 3: Using the Golang Net/URL Package to Decode the URL

We can decode the URL in Go using the net/url package which has the Query() function to do this. Take a look at the subsequent program where the given URL is decoded:

package main
import (
"fmt"
"net/url"
)
func main() {
MyURL := &url.URL{
Scheme: "https",
Host:   "www.gmail.com",
Path:   "/search",
}

MyQuery := MyURL.Query()
MyQuery.Set("MyQuery", "golang")
MyURL.RawQuery = MyQuery.Encode()
fmt.Println(MyURL.String())
}

We begin with initializing a “url.URL” struct called “MyURL” using a pointer. This struct represents a URL and has various fields to store different components of the URL such as scheme, host, and path. Then, we construct the URL where the scheme is set to “https”, the host is set to “www.gmail.com“, and the path is set to “/search”.

Next, we use the Query() method on “MyURL” to get the “url.Values” object that represents the URL’s query arguments. The returned “url.Values” object is stored in the “MyQuery” variable. Then, we use the Set() method which adds a query parameter to “MyQuery”. In this case, the key is “MyQuery” and the value is “golang”.

After adding the query parameter, the Encode() method is called on “MyQuery” to URL-encode the query parameters. The URL-encoded query string is then assigned to MyURL.RawQuery which stores the raw URL-encoded query string. Finally, the String() method is defined which is called on “MyURL” to obtain the complete URL string representation including the scheme, host, path, and query string.

The output of the program displays the complete URL string on the subsequent screen:

Example 4: Using the Golang Net/URL Package to Check the Relative or Absolute URL

Moreover, we can identify the relative and absolute URL using the net/url package. An absolute URL is a complete URL that includes the scheme (e.g., “http,” “https”), host, and path. On the other hand, a relative URL is a URL that is relative to a base URL and does not include the scheme or host.

package main
import (
"fmt"
"net/url"
)
func ExampleURL() {
URLIs:= url.URL{Host: "MyWebsite.com", Path: "test"}
fmt.Println("The Url is",URLIs.IsAbs())
}
func main() {
ExampleURL()
}

We have an ExampleURL() function with the URLIs variable of type “url.URL” that is declared and initialized. It represents a URL and has two fields: “Host” and “Path”. Here, the “Host” is set to “MyWebsite.com” and the Path is set to “test”. After that, we call the IsAbs() method on the URLIs variable which checks whether the URL is an absolute URL or a relative URL. It provides a Boolean result that specifies if the URL is absolute (true) or relative (false).

Since the provided URL in the program is relative(false), the output displays the message accordingly:

Example 5: Using the Golang Net/URL Package to Set the URL Character into the Encoded String Format

The Go net/url package provides the PathEscape() function which is used to URL-encode a string so that it can be safely used as a path segment in a URL. The PathEscape() function is utilized in the following program to demonstrate it efficiently:

package main
import (
  "fmt"
  "net/url"
)
func main() {
  URLStr := "https://meet.google.com"
  encodedString := url.PathEscape(URLStr)
  fmt.Println(encodedString)
}

Here, we declare the “URLStr” variable and assign it with the value of the URL path segment. Then, we have the PathEscape() function from the URL package which takes a string as input and returns an encoded version of the string that is safe to be used as a path segment in a URL. Next, we pass the “URLStr” variable as an argument to PathEscape(), and the returned encoded string is stored in the “encodedString” variable.

Here, we have the output which has a URL-encoded version of the “URLStr” path segment:

Conclusion

Go’s net/url package provides a robust and user-friendly set of tools to work with URLs. Here, numerous functions are discussed which are supported by the net/url package. We gained the skills in handling URLs by grasping their functionalities through real-world situations. Now, we are prepared to take on any URL-related operations that comes in the way by integrating the potency of Go with the capabilities of the net/url package.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content