Skip to main content
URLs provide a uniform way to locate resources. Here’s how to parse URLs in Go using the net/url package.

Parsing a URL

Parse a URL that includes scheme, authentication info, host, port, path, query params, and fragment:
s := "postgres://user:[email protected]:5432/path?k=v#f"

u, err := url.Parse(s)
if err != nil {
    panic(err)
}

URL Components

Scheme

Accessing the scheme is straightforward:
fmt.Println(u.Scheme)
// Output: postgres

Authentication

User contains all authentication info:
fmt.Println(u.User)
// Output: user:pass

fmt.Println(u.User.Username())
// Output: user

p, _ := u.User.Password()
fmt.Println(p)
// Output: pass

Host and Port

The Host contains both hostname and port. Use net.SplitHostPort to extract them:
fmt.Println(u.Host)
// Output: host.com:5432

host, port, _ := net.SplitHostPort(u.Host)
fmt.Println(host)
// Output: host.com

fmt.Println(port)
// Output: 5432

Path and Fragment

Extract the path and fragment:
fmt.Println(u.Path)
// Output: /path

fmt.Println(u.Fragment)
// Output: f

Query Parameters

Raw Query String

Get query params as a raw string:
fmt.Println(u.RawQuery)
// Output: k=v

Parsed Query Map

Parse query params into a map. Values are slices of strings:
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
// Output: map[k:[v]]

fmt.Println(m["k"][0])
// Output: v
Query param maps are from strings to slices of strings. Index into [0] if you only want the first value.

URL Structure

scheme://[userinfo@]host/path[?query][#fragment]
The protocol (http, https, postgres, etc.)
Optional username and password
Hostname and optional port
Path to the resource
Key-value pairs after ’?’
Section identifier after ’#‘

URL Fields

Scheme
string
The protocol scheme (http, https, etc.)
User
*Userinfo
Username and password information
Host
string
Hostname and port (host:port)
Path
string
Path portion of the URL
RawQuery
string
Encoded query values without ’?’
Fragment
string
Fragment identifier without ’#‘

Building URLs

Construct URLs programmatically:
u := &url.URL{
    Scheme:   "https",
    Host:     "example.com",
    Path:     "/api/v1/users",
    RawQuery: "active=true&limit=10",
}

fmt.Println(u.String())
// Output: https://example.com/api/v1/users?active=true&limit=10

Package Reference

Build docs developers (and LLMs) love