ZetCode

Go URL

last modified November 19, 2026 Go 1.27

In this article we show how to work with URLs in Go using the net/url package. We parse URLs into parts, read and build query strings, escape text for paths and queries, join paths, resolve relative links, handle credentials and parse errors, and finally normalize links found on a web page.

All examples in this article were run with Go 1.27.0. They only process strings, so they need no network access.

The structure of a URL

A URL (Uniform Resource Locator) identifies a resource and tells how to reach it. Its general form, defined in RFC 3986, is:

scheme://user:password@host:port/path?query#fragment

Only the scheme and, for most schemes, the host are required. The query holds key=value pairs separated by &, and the fragment points to a part of the document; browsers do not send it to the server. Characters that have a special meaning, such as spaces, ? or &, must be percent-encoded: a space becomes %20.

The net/url package parses a string into a url.URL struct with a field for each part, and turns the struct back into a string. Doing this with string functions such as strings.Split breaks on the first URL with an escaped character or a port.

Parsing a URL

The url.Parse function splits a URL into its parts.

parse_url.go
package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {

    raw := "https://lucia:s3cret@shop.example.com:8443/books/go?lang=en&page=2#reviews"

    u, err := url.Parse(raw)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("scheme:  ", u.Scheme)
    fmt.Println("user:    ", u.User.Username())
    fmt.Println("host:    ", u.Host)
    fmt.Println("hostname:", u.Hostname())
    fmt.Println("port:    ", u.Port())
    fmt.Println("path:    ", u.Path)
    fmt.Println("query:   ", u.RawQuery)
    fmt.Println("fragment:", u.Fragment)
}

The URL contains every part from the previous section.

u, err := url.Parse(raw)

url.Parse returns a *url.URL, or an error if the string is not a valid URL.

fmt.Println("host:    ", u.Host)
fmt.Println("hostname:", u.Hostname())
fmt.Println("port:    ", u.Port())

The Host field holds the host together with the port. The Hostname and Port methods split them; they also handle IPv6 addresses in brackets, such as [::1]:8080.

fmt.Println("query:   ", u.RawQuery)

RawQuery is the query string as it appears in the URL, still encoded and without the question mark. The next section decodes it.

$ go run parse_url.go
scheme:   https
user:     lucia
host:     shop.example.com:8443
hostname: shop.example.com
port:     8443
path:     /books/go
query:    lang=en&page=2
fragment: reviews

Query parameters

The Query method decodes the query string into a url.Values value.

query_values.go
package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {

    u, err := url.Parse("https://example.com/search?q=go+url&tag=net&tag=http&empty=")
    if err != nil {
        log.Fatal(err)
    }

    q := u.Query()
    fmt.Println(q)

    fmt.Printf("q: %q\n", q.Get("q"))
    fmt.Printf("tag: %q\n", q.Get("tag"))
    fmt.Printf("all tags: %q\n", q["tag"])

    fmt.Printf("empty: %q, present: %t\n", q.Get("empty"), q.Has("empty"))
    fmt.Printf("page: %q, present: %t\n", q.Get("page"), q.Has("page"))
}

url.Values is a map[string][]string, because a key may occur in a query more than once.

fmt.Printf("q: %q\n", q.Get("q"))

The values are decoded: the + in go+url stands for a space in a query string.

fmt.Printf("tag: %q\n", q.Get("tag"))
fmt.Printf("all tags: %q\n", q["tag"])

Get returns the first value of a key. To get all of them, we index the map directly.

fmt.Printf("empty: %q, present: %t\n", q.Get("empty"), q.Has("empty"))

Get returns an empty string both for a key with an empty value and for a missing key. Has tells the two cases apart.

$ go run query_values.go
map[empty:[] q:[go url] tag:[net http]]
q: "go url"
tag: "net"
all tags: ["net" "http"]
empty: "", present: true
page: "", present: false

Building a URL

To build a URL, we fill a url.URL struct and call its String method. The struct takes care of the escaping.

build_url.go
package main

import (
    "fmt"
    "net/url"
)

func main() {

    params := url.Values{}
    params.Set("q", "go & rust")
    params.Add("tag", "net")
    params.Add("tag", "web")
    params.Set("page", "1")

    u := url.URL{
        Scheme:   "https",
        Host:     "example.com",
        Path:     "/search results",
        RawQuery: params.Encode(),
        Fragment: "top",
    }

    fmt.Println(params.Encode())
    fmt.Println(u.String())
}

The query is built first as url.Values.

params.Set("q", "go & rust")
params.Add("tag", "net")
params.Add("tag", "web")

Set replaces all values of a key, Add appends a value. The & inside the search text must not be taken for a separator.

RawQuery: params.Encode(),

Encode escapes the keys and values and sorts the keys, so the same parameters always give the same string. The & in the value became %26.

Path:     "/search results",

The Path field holds the decoded path; String escapes the space as %20.

$ go run build_url.go
page=1&q=go+%26+rust&tag=net&tag=web
https://example.com/search%20results?page=1&q=go+%26+rust&tag=net&tag=web#top

Changing the query

A common task is to change a few parameters of an existing URL, for example to build the link to the next page of results.

edit_query.go
package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {

    u, err := url.Parse("https://example.com/books?sort=title&page=1&debug=1")
    if err != nil {
        log.Fatal(err)
    }

    q := u.Query()
    q.Set("page", "2")
    q.Add("author", "Rob Pike")
    q.Del("debug")

    fmt.Println(u)

    u.RawQuery = q.Encode()
    fmt.Println(u)
}

The program sets the page, adds an author filter and removes a debug flag.

q := u.Query()
q.Set("page", "2")
q.Add("author", "Rob Pike")
q.Del("debug")

Query returns a new copy of the parameters each time it is called. Changing the copy does not change the URL, as the first line of the output shows.

u.RawQuery = q.Encode()

The changes take effect only after the encoded parameters are stored back in RawQuery. The keys are now sorted, which does not change the meaning of the query.

$ go run edit_query.go
https://example.com/books?sort=title&page=1&debug=1
https://example.com/books?author=Rob+Pike&page=2&sort=title

Escaping

When we insert text into a URL ourselves, we must escape it. The rules differ for paths and queries.

escaping.go
package main

import (
    "fmt"
    "net/url"
)

func main() {

    inputs := []string{"a b", "a+b", "a/b", "a?b&c=d", "50%", "žltá"}

    fmt.Printf("%-10s %-16s %s\n", "input", "QueryEscape", "PathEscape")

    for _, s := range inputs {
        fmt.Printf("%-10s %-16s %s\n", s, url.QueryEscape(s), url.PathEscape(s))
    }

    fmt.Println()

    for _, s := range []string{"a+b%20c", "caf%C3%A9", "100%"} {

        q, err := url.QueryUnescape(s)
        if err != nil {
            fmt.Println(err)
            continue
        }

        p, _ := url.PathUnescape(s)
        fmt.Printf("%-10s query: %-10q path: %q\n", s, q, p)
    }
}

The program escapes several strings in both ways, and then decodes three escaped strings.

url.QueryEscape(s), url.PathEscape(s)

QueryEscape prepares a query key or value. A space becomes +, so a real plus sign must become %2B. PathEscape prepares one path segment. A space becomes %20, and / is escaped so that it does not split the segment; & and = are allowed in paths. Non-ASCII characters are encoded as UTF-8 bytes in both cases.

q, err := url.QueryUnescape(s)

The unescape functions reverse the process; only QueryUnescape turns + into a space. A % that is not followed by two hexadecimal digits is an error. PathUnescape fails on the same input, so we can ignore its error after QueryUnescape has succeeded.

$ go run escaping.go
input      QueryEscape      PathEscape
a b        a+b              a%20b
a+b        a%2Bb            a+b
a/b        a%2Fb            a%2Fb
a?b&c=d    a%3Fb%26c%3Dd    a%3Fb&c=d
50%        50%25            50%25
žltá       %C5%BElt%C3%A1   %C5%BElt%C3%A1

a+b%20c    query: "a b c"    path: "a+b c"
caf%C3%A9  query: "café"     path: "café"
invalid URL escape "%"

Paths

Since Path is stored decoded, an escaped slash and a real slash look the same in it. The program also joins path segments to a base URL.

paths.go
package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {

    u, err := url.Parse("https://example.com/files/reports%2F2026/q1%20summary.pdf")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Path:       ", u.Path)
    fmt.Println("RawPath:    ", u.RawPath)
    fmt.Println("EscapedPath:", u.EscapedPath())

    base, err := url.Parse("https://api.example.com/v2/")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(base.JoinPath("users", "42", "orders"))
    fmt.Println(base.JoinPath("users/", "../admin"))
    fmt.Println(base.JoinPath("a b", "c/d"))

    s, err := url.JoinPath("https://api.example.com/v2", "items/")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(s)
}

The first URL has a file name with a space and a directory name that contains an escaped slash.

fmt.Println("Path:       ", u.Path)
fmt.Println("RawPath:    ", u.RawPath)
fmt.Println("EscapedPath:", u.EscapedPath())

In Path, reports%2F2026 became reports/2026, an extra directory level. When the decoded form differs from the default encoding, Parse keeps the original in RawPath. Code should call EscapedPath, which uses RawPath when it is valid; String does the same.

fmt.Println(base.JoinPath("users", "42", "orders"))
fmt.Println(base.JoinPath("users/", "../admin"))

JoinPath returns a new URL with the elements appended to the path. It puts exactly one slash between the elements and cleans . and ..; note that ../admin stays under /v2. The elements are not escaped path segments: a / in an element adds a level, while a space is escaped.

s, err := url.JoinPath("https://api.example.com/v2", "items/")

The url.JoinPath function does the same for a string. It keeps the trailing slash of the last element.

$ go run paths.go
Path:        /files/reports/2026/q1 summary.pdf
RawPath:     /files/reports%2F2026/q1%20summary.pdf
EscapedPath: /files/reports%2F2026/q1%20summary.pdf
https://api.example.com/v2/users/42/orders
https://api.example.com/v2/admin
https://api.example.com/v2/a%20b/c/d
https://api.example.com/v2/items/

Resolving relative links

Links in HTML pages are often relative to the page. The Parse method of a base URL resolves them the way a browser does.

resolve.go
package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {

    base, err := url.Parse("https://example.com/docs/guide/intro.html?v=2")
    if err != nil {
        log.Fatal(err)
    }

    refs := []string{
        "setup.html",
        "../api/net.html",
        "/about",
        "?v=3",
        "#install",
        "//cdn.example.org/app.js",
        "mailto:info@example.com",
    }

    for _, ref := range refs {

        u, err := base.Parse(ref)
        if err != nil {
            fmt.Println(err)
            continue
        }

        fmt.Printf("%-26s %s\n", ref, u)
    }
}

The base URL is the address of a page, and the references are links that the page could contain.

u, err := base.Parse(ref)

base.Parse(ref) parses the reference and resolves it against the base; base.ResolveReference does the same for an already parsed URL. The rules come from section 5 of RFC 3986.

A plain file name replaces the last path segment, .. goes one directory up and a leading slash starts from the root. A query-only reference keeps the path, and a fragment keeps the query too. A reference that starts with // keeps only the scheme, and an absolute URL such as the mailto link replaces the base entirely.

$ go run resolve.go
setup.html                 https://example.com/docs/guide/setup.html
../api/net.html            https://example.com/docs/api/net.html
/about                     https://example.com/about
?v=3                       https://example.com/docs/guide/intro.html?v=3
#install                   https://example.com/docs/guide/intro.html?v=2#install
//cdn.example.org/app.js   https://cdn.example.org/app.js
mailto:info@example.com    mailto:info@example.com

User information

URLs of databases and other services often contain a user name and a password. The User field holds them as a *url.Userinfo.

userinfo.go
package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {

    u, err := url.Parse("postgres://app:p%40ss@db.example.com:5432/shop?sslmode=require")
    if err != nil {
        log.Fatal(err)
    }

    password, ok := u.User.Password()
    fmt.Printf("user %q, password %q, set: %t\n", u.User.Username(), password, ok)

    fmt.Println("redacted:", u.Redacted())

    u.User = url.UserPassword("report", "a:b@c/d")
    fmt.Println(u)

    u.User = url.User("readonly")
    fmt.Println(u)
}

The password in the connection URL contains an @, which must be escaped as %40.

password, ok := u.User.Password()

Password returns the decoded password and whether one was set.

fmt.Println("redacted:", u.Redacted())

Redacted returns the URL with the password replaced by xxxxx. Use it whenever a URL goes into a log or an error message.

u.User = url.UserPassword("report", "a:b@c/d")

url.UserPassword and url.User create the user information from plain strings, and String escapes the characters that would break the URL.

$ go run userinfo.go
user "app", password "p@ss", set: true
redacted: postgres://app:xxxxx@db.example.com:5432/shop?sslmode=require
postgres://report:a%3Ab%40c%2Fd@db.example.com:5432/shop?sslmode=require
postgres://readonly@db.example.com:5432/shop?sslmode=require

Parse errors

url.Parse is lenient: it accepts relative references and even a space in the path. It rejects only strings that cannot be split into parts.

parse_errors.go
package main

import (
    "errors"
    "fmt"
    "net/url"
)

func main() {

    inputs := []string{
        "https://example.com/a b",
        "https://example.com/%zz",
        "https://[::1",
        "https://example.com:http/",
        " https://example.com",
        "example.com/path",
    }

    for _, s := range inputs {

        u, err := url.Parse(s)

        var urlErr *url.Error
        if errors.As(err, &urlErr) {
            fmt.Printf("%-28q %s: %v\n", s, urlErr.Op, urlErr.Err)
            continue
        }

        fmt.Printf("%-28q ok, scheme %q, host %q, path %q\n", s, u.Scheme, u.Host, u.Path)
    }

    _, err := url.ParseRequestURI("example.com/path")
    fmt.Println("ParseRequestURI:", err)
}

The program parses six strings and prints the parts or the reason for the error.

var urlErr *url.Error
if errors.As(err, &urlErr) {

Errors are of type *url.Error, which holds the operation, the URL and the underlying error.

The leading space makes the whole string a relative path, whose first segment contains a colon. example.com/path without a scheme is parsed as a path, not as a host; this is a common mistake with addresses typed by users. url.ParseRequestURI is stricter: it accepts only absolute URLs and absolute paths, and it is what an HTTP server uses for the request target.

$ go run parse_errors.go
"https://example.com/a b"    ok, scheme "https", host "example.com", path "/a b"
"https://example.com/%zz"    parse: invalid URL escape "%zz"
"https://[::1"               parse: missing ']' in host
"https://example.com:http/"  parse: invalid port ":http" after host
" https://example.com"       parse: first path segment in URL cannot contain colon
"example.com/path"           ok, scheme "", host "", path "example.com/path"
ParseRequestURI: parse "example.com/path": invalid URI for request

Normalizing links

A web crawler collects links from pages and must not visit the same page twice. The same page can be written in many ways, so the links are first normalized: resolved, lower-cased, stripped of default ports, credentials and fragments, and given a sorted query.

normalize_links.go
package main

import (
    "fmt"
    "log"
    "net/url"
    "strings"
)

var defaultPorts = map[string]string{"http": ":80", "https": ":443"}

func normalize(page *url.URL, href string) (string, bool) {

    u, err := page.Parse(strings.TrimSpace(href))
    if err != nil {
        return "", false
    }

    port, ok := defaultPorts[u.Scheme]
    if !ok {
        return "", false
    }

    u.Host = strings.TrimSuffix(strings.ToLower(u.Host), port)
    if u.Path == "" {
        u.Path = "/"
    }

    u.User = nil
    u.Fragment = ""
    u.RawQuery = u.Query().Encode()

    return u.String(), true
}

func main() {

    page, err := url.Parse("https://Example.com/blog/post.html")
    if err != nil {
        log.Fatal(err)
    }

    hrefs := []string{
        "next.html",
        "  ./next.html#comments ",
        "https://EXAMPLE.com:443/blog/next.html",
        "/search?q=go&lang=en",
        "/search?lang=en&q=go",
        "http://example.com:80",
        "https://admin:pw@example.com/",
        "https://[::1]:443/status",
        "javascript:void(0)",
        "mailto:info@example.com",
        "https://example.com/%zz",
    }

    seen := make(map[string]bool)

    for _, href := range hrefs {

        link, ok := normalize(page, href)
        if !ok {
            fmt.Printf("skipped   %q\n", href)
            continue
        }

        if seen[link] {
            fmt.Printf("duplicate %s\n", link)
            continue
        }

        seen[link] = true
        fmt.Printf("link      %s\n", link)
    }
}

The normalize function turns a link found on a page into a canonical absolute URL, or reports that it should be skipped.

u, err := page.Parse(strings.TrimSpace(href))

Attribute values in HTML often contain extra spaces. The link is resolved against the page URL as in the previous sections.

port, ok := defaultPorts[u.Scheme]
if !ok {
    return "", false
}

u.Host = strings.TrimSuffix(strings.ToLower(u.Host), port)

Only http and https links are kept; Parse has already lower-cased the scheme. Host names are not case-sensitive, so we lower-case them, and a default port such as :443 for HTTPS is removed. Removing the suffix from the whole host also works for IPv6 addresses, whose brackets must stay.

u.RawQuery = u.Query().Encode()

Re-encoding the query sorts the keys, so ?q=go&lang=en and ?lang=en&q=go give the same link. The map of seen links then filters out the duplicates.

$ go run normalize_links.go
link      https://example.com/blog/next.html
duplicate https://example.com/blog/next.html
duplicate https://example.com/blog/next.html
link      https://example.com/search?lang=en&q=go
duplicate https://example.com/search?lang=en&q=go
link      http://example.com/
link      https://example.com/
link      https://[::1]/status
skipped   "javascript:void(0)"
skipped   "mailto:info@example.com"
skipped   "https://example.com/%zz"

Source

Go net/url package - reference
RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax

In this article we have worked with URLs in Go: parsing, query parameters, building and changing URLs, escaping, paths, relative links, user information, parse errors and link normalization. The GET/POST request article sends query parameters to a server, the HTTP server article reads them in handlers, and the net/html article extracts links from HTML pages.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.