Go by Example: URL Parsing

The url package in Go provides functions for parsing and manipulating URLs.

Here’s an example that demonstrates how to use the url package to parse URLs:

package main

import (
	"fmt"
	"net/url"
)

func main() {
	// Parse a URL string
	u, err := url.Parse("https://www.example.com/path?q=value")
	if err != nil {
		fmt.Println("Error parsing URL:", err)
		return
	}

	// Access components of the URL
	fmt.Println("Scheme:", u.Scheme)
	fmt.Println("Host:", u.Host)
	fmt.Println("Path:", u.Path)

	// Access the query parameters
	q := u.Query()
	fmt.Println("Query parameters:", q)
	fmt.Println("Value of 'q':", q.Get("q"))

	// Modify the URL
	u.Path = "/new/path"
	q.Add("key", "value")
	u.RawQuery = q.Encode()
	fmt.Println("Modified URL:", u.String())
}

In this example, the url.Parse function is used to parse a URL string. If the parsing fails, an error is returned.

Once the URL is parsed, you can access its components, such as the scheme, host, and path, using the fields of the url.URL struct. You can also access the query parameters using the Query method, which returns a Values map.

Finally, you can modify the URL by changing its fields and encoding the modified query parameters using the Encode method of the Values map. The String method of the url.URL struct can then be used to get the string representation of the modified URL.

The output of this program will be something like:

Scheme: https
Host: www.example.com
Path: /path
Query parameters: map[q:[value]]
Value of 'q': value
Modified URL: https://www.example.com/new/path?key=value&q=value

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *