Parsing URLs

Overview

When working with a URL in your Hugo templates, the urls.Parse function provides access to any of the URL components. A URL may be relative (a path, without a host) or absolute (starting with a scheme).

See the Go documentation for more information about the net/url package.

Examples

Parse an HTTP URL

{{ $url := "https://john:secret@example.org:123/foo/bar?a=1&a=2&b=3#baz" }}
{{ $u := urls.Parse $url }}

{{ $u.String }} --> https://john:secret@example.org:123/foo/bar?a=1&a=2&b=3#baz (string)
{{ $u.Redacted }} --> https://john:xxxxx@example.org:123/foo/bar?a=1&a=2&b=3#baz (string)
{{ $u.IsAbs }} --> true (bool)
{{ $u.Scheme }} --> https (string)
{{ $u.User.String }} --> john:secret (string)
{{ $u.User.Username }} --> john (string)
{{ $u.Host }} --> example.org:123 (string)
{{ $u.Hostname }} --> example.org (string)
{{ $u.Port }} --> 123 (string)
{{ $u.RequestURI }} --> /foo/bar?a=1&a=2&b=3 (string)
{{ $u.Path }} --> /foo/bar (string)
{{ $u.EscapedPath }} --> /foo/bar (string)
{{ $u.RawQuery }} --> a=1&a=2&b=3 (string)
{{ $u.Query }} --> map[a:[1 2] b:[3]] (url.Values)
{{ $u.Query.a }} --> [1 2] ([]string)
{{ $u.Query.b }} --> [3] ([]string)
{{ $u.Query.Get "a" }} --> 1 (string)
{{ $u.Query.Get "b" }} --> 3 (string)
{{ $u.Query.Has "c" }} --> false (bool)
{{ $u.Fragment }} --> baz (string)
{{ $u.EscapedFragment }} --> baz (string)

Parse an email URL

{{ $url := "mailto:john@example.org?subject=Please%20call" }}
{{ $u := urls.Parse $url }}

{{ $u.String }} --> mailto:john@example.org?subject=Please%20call (string)
{{ $u.IsAbs }} --> true (bool)
{{ $u.Scheme }} --> mailto (string)
{{ $u.Opaque }} --> john@example.org (string)
{{ $u.RequestURI }} --> john@example.org?subject=Please%20call (string)
{{ $u.RawQuery }} --> subject=Please%20call (string)
{{ $u.Query }} --> map[subject:[Please call]] (url.Values)
{{ $u.Query.subject }} --> [Please call] ([]string)
{{ $u.Query.Get "subject" }} --> Please call (string)
{{ $u.Query.Has "subject" }} --> true (bool)

Resolve a reference

The ResolveReference method lets you create a new URL structure from a base and reference.

{{ $base := urls.Parse "https://example.org:123/foo/bar/" }}
{{ $reference := urls.Parse "../search?q=hugo" }}
{{ $u := $base.ResolveReference $reference }}

{{ $u.String }} --> https://example.org:123/foo/search?q=hugo (string)
{{ $u.Redacted }} --> https://example.org:123/foo/search?q=hugo (string)
{{ $u.IsAbs }} --> true (bool)
{{ $u.Scheme }} --> https (string)
{{ $u.Host }} --> example.org:123 (string)
{{ $u.Hostname }} --> example.org (string)
{{ $u.Port }} --> 123 (string)
{{ $u.RequestURI }} --> /foo/search?q=hugo (string)
{{ $u.Path }} --> /foo/search (string)
{{ $u.EscapedPath }} --> /foo/search (string)
{{ $u.RawQuery }} --> q=hugo (string)
{{ $u.Query }} --> map[q:[hugo]] (url.Values)
{{ $u.Query.q }} --> [hugo] ([]string)
{{ $u.Query.Get "q" }} --> hugo (string)
{{ $u.Query.Has "q" }} --> true (bool)
Last modified: