URL Parsing in Go

Go: URL Parsing

Go's net/url package provides functionality for parsing URLs and working with their components. The package includes a URL type representing a parsed URL, and functions for parsing and building URLs.

How to parse a URL in Go

    package main

    import (
        "fmt"
        "net/url"
    )

    func main() {
        str := "https://www.example.com/path?query=value#fragment"
        parsedUrl, err := url.Parse(str)
        if err != nil {
            fmt.Println("Failed to parse URL:", err)
            return
        }
        fmt.Println(parsedUrl.Scheme)   // Output: https
        fmt.Println(parsedUrl.Host)     // Output: www.example.com
        fmt.Println(parsedUrl.Path)     // Output: /path
        fmt.Println(parsedUrl.RawQuery) // Output: query=value
        fmt.Println(parsedUrl.Fragment) // Output: fragment
    }

In this example, the url.Parse() function is used to parse the URL string https://www.example.com/path?query=value#fragment. The function returns two values: a URL struct representing the parsed URL, and an error if the string could not be parsed.

You can then access the components of the parsed URL using the fields of the URL struct, such as Scheme, Host, Path, RawQuery, and Fragment.

Here are some other functions you can use for working with URLs in Go:

  • url.QueryEscape(s string) string: escapes a string so it can be safely placed inside a URL query parameter.
  • url.QueryUnescape(s string) (string, error): unescapes a string previously escaped by url.QueryEscape().
  • url.Values: a type representing URL query parameters as key-value pairs. You can use the Get(), Set(), and Add() methods to manipulate query parameters.
  • url.ParseRequestURI(s string) (*url.URL, error): parses a URI as if it were a request URL, without a leading slash.

Note that the net/url package only handles parsing and manipulation of the URL string itself. If you need to actually make HTTP requests or work with web servers, you should use the net/http package.

Previous Article

Next Article