net/url

net/url Parse versus ParseRequestURI, QueryEscape versus PathEscape, and why parsing a URL is not a security check.

The net/url package parses URLs and escapes query or path text. Import it as "net/url". It is not an HTTP client and the examples here do not make network requests.

Parse is not a security check and it is not a general validator. Official documentation says a hostname and path without a scheme is invalid but may not necessarily return an error, because of parsing ambiguities. The examples below show strings that Parse accepts, including "not a url" and "javascript:alert(1)". Treat a successful parse as a structured split of the input, not as proof that the value is safe to request or to render.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
url.Parse, URL.String, URL.Query, URL.RequestURI, URL.RedactedParse a URL into fields, reassemble it, read query values, or hide a password.
url.Parse, url.ParseRequestURI, URL.EscapedPathParse can accept strings that are not valid request URIs and does not prove that a value is safe. ParseRequestURI is stricter.
url.QueryEscape, url.PathEscape, Values.Encode, URL.JoinPathEscape a string for a query or a path segment, encode query values, or join path elements onto a URL.

Parse and ParseRequestURI

Parse accepts an absolute URL or a relative path and fills a URL struct. Host includes a port when one is present. Path is stored decoded, so /%47%6f%2f becomes /Go/ and you cannot tell which slashes were originally %2F unless you use EscapedPath. Query parses RawQuery into Values and silently drops malformed pairs; use ParseQuery when you need the error. String reassembles the URL. Redacted hides a password. RequestURI is the path and query that would be used in an HTTP request.

ParseRequestURI is stricter: it expects an absolute URI or an absolute path, as in an HTTP request, and it assumes there is no #fragment. "not a url" fails that check even though Parse succeeds and stores the string in Path. A scheme without a slash, such as javascript:alert(1), is stored as scheme plus Opaque, not as a host and path.

url.Parse, URL.String, URL.Query, URL.RequestURI, URL.Redacted

func Parse(rawURL string) (*URL, error)
func (u *URL) String() string
func (u *URL) Query() Values
func (u *URL) RequestURI() string
func (u *URL) Redacted() string

Parse a URL into fields, reassemble it, read query values, or hide a password.

ParameterDescription
rawURLThe input string. It may be relative or absolute. This helper does not fetch the URL.

Returns: Parse returns a *URL and an error. String and RequestURI return reassembled strings. Query returns Values derived from RawQuery. Redacted returns a copy with a password replaced by xxxxx.

Errors

  • error — Parse returns an error for some invalid inputs, but a missing scheme is not always rejected. See the next example.
  • User.String() in this example is "user:pass". Prefer Redacted when logging a URL that may contain a password.
  • Query silently discards malformed value pairs. ParseQuery reports the first decoding error and still returns the valid parameters.
go
package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, err := url.Parse("https://user:[email protected]:443/a/b?q=1&q=2#frag")
	fmt.Println(err)
	fmt.Println(u.Scheme, u.User, u.Host, u.Path, u.RawQuery, u.Fragment)
	fmt.Println(u.Query()["q"])
	fmt.Println(u.String())
	fmt.Println(u.RequestURI())
	fmt.Println(u.Redacted())
}

Expected output

<nil>
https user:pass example.com:443 /a/b q=1&q=2 frag
[1 2]
https://user:[email protected]:443/a/b?q=1&q=2#frag
/a/b?q=1&q=2
https://user:[email protected]:443/a/b?q=1&q=2#frag

Official documentation →

url.Parse, url.ParseRequestURI, URL.EscapedPath

func Parse(rawURL string) (*URL, error)
func ParseRequestURI(rawURL string) (*URL, error)
func (u *URL) EscapedPath() string

Parse can accept strings that are not valid request URIs and does not prove that a value is safe. ParseRequestURI is stricter.

ParameterDescription
rawURLParseRequestURI treats the string as an absolute URI or an absolute path and assumes no #fragment.

Returns: Both functions return a *URL and an error. EscapedPath returns the path with the original encoding preserved when RawPath was set.

Errors

  • error — ParseRequestURI("not a url") returns parse "not a url": invalid URI for request and a nil *URL. Parse of the same string returns a nil error.
  • Parse("not a url") stores the text in Path. String then percent-encodes the space, producing not%20a%20url. That is still not a validity or safety judgement.
  • Parse("javascript:alert(1)") sets Scheme to "javascript" and Opaque to "alert(1)". Parse("example.com/path") does not fill Host; the whole string is Path.
  • Path for https://example.com/%47%6f%2f is /Go/. EscapedPath keeps /%47%6f%2f.
go
package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, err := url.Parse("not a url")
	fmt.Printf("%v %q %q %q\n", err, u.Scheme, u.Host, u.Path)
	fmt.Println(u.String())

	u, err = url.Parse("javascript:alert(1)")
	fmt.Printf("%v %q %q %q\n", err, u.Scheme, u.Opaque, u.Path)

	u, err = url.Parse("example.com/path")
	fmt.Printf("%v %q %q\n", err, u.Host, u.Path)

	u, err = url.ParseRequestURI("not a url")
	fmt.Printf("%v %v\n", err, u)

	u, err = url.Parse("https://example.com/%47%6f%2f")
	fmt.Printf("%q %q\n", u.Path, u.EscapedPath())
}

Expected output

<nil> "" "" "not a url"
not%20a%20url
<nil> "javascript" "alert(1)" ""
<nil> "" "example.com/path"
parse "not a url": invalid URI for request <nil>
"/Go/" "/%47%6f%2f"

Official documentation →

QueryEscape, PathEscape, and Values

QueryEscape escapes text for a query string and encodes a space as "+". PathEscape escapes text for a path segment and encodes a space as "%20". Both encode "/" as "%2F", because a slash is special in a path and is also encoded in a query. The words "safely placed" in the official documentation mean "encoded for that URL component"; they are not a promise that the surrounding application is safe.

Values is a map of string slices and is case-sensitive. Encode writes key=value pairs in key-sorted order using query escaping, so a space becomes "+". JoinPath returns a new URL with extra path elements cleaned of "." and ".."; it does not mutate the receiver.

url.QueryEscape, url.PathEscape, Values.Encode, URL.JoinPath

func QueryEscape(s string) string
func PathEscape(s string) string
func (v Values) Encode() string
func (u *URL) JoinPath(elem ...string) *URL

Escape a string for a query or a path segment, encode query values, or join path elements onto a URL.

ParameterDescription
sThe raw text to escape. QueryEscape uses "+" for a space; PathEscape uses "%20".
vA Values map, typically from URL.Query or ParseQuery. Encode sorts the keys.
elemPath elements joined to u. Sequences of slashes are collapsed, and "." or ".." are cleaned.

Returns: QueryEscape, PathEscape, and Encode return encoded strings. JoinPath returns a new *URL.

  • Values{"q": {"a b"}, "n": {"2"}}.Encode() is n=2&q=a+b because keys are sorted and spaces use query escaping.
  • JoinPath("..", "d") on https://example.com/a yields https://example.com/d and leaves the original URL unchanged.
go
package main

import (
	"fmt"
	"net/url"
)

func main() {
	fmt.Println(url.QueryEscape("a b/c"))
	fmt.Println(url.PathEscape("a b/c"))
	v := url.Values{"q": {"a b"}, "n": {"2"}}
	fmt.Println(v.Encode())
	u, _ := url.Parse("https://example.com/a")
	fmt.Println(u.JoinPath("b", "c").String())
	fmt.Println(u.JoinPath("..", "d").String())
}

Expected output

a+b%2Fc
a%20b%2Fc
n=2&q=a+b
https://example.com/a/b/c
https://example.com/d

Official documentation →