net/url
Index
- func QueryEscape(s string) string
- func QueryUnescape(s string) (string, error)
- func Parse(rawURL string) (*URL, error)
- func ParseRequestURI(rawURL string) (*URL, error)
- func User(username string) *Userinfo
- func UserPassword(username, password string) *Userinfo
- func ParseQuery(query string) (Values, error)
- type Error
- func (e *Error) Error() string
- func (e *Error) Temporary() bool
- func (e *Error) Timeout() bool
- func (e *Error) Unwrap() error
- type URL
- func Parse(rawURL string) (*URL, error)
- func ParseRequestURI(rawURL string) (*URL, error)
- func (u *URL) EscapedFragment() string
- func (u *URL) EscapedPath() string
- func (u *URL) Hostname() string
- func (u *URL) IsAbs() bool
- func (u *URL) JoinPath(elem ...string) *URL
- func (u *URL) MarshalBinary() (text []byte, err error)
- func (u *URL) Parse(ref string) (*URL, error)
- func (u *URL) Port() string
- func (u *URL) Query() Values
- func (u *URL) Redacted() string
- func (u *URL) RequestURI() string
- func (u *URL) ResolveReference(ref *URL) *URL
- func (u *URL) String() string
- func (u *URL) UnmarshalBinary(text []byte) error
- type Values
Functions
func QueryEscape
1func QueryEscape(s string) string
QueryEscape escapes the string so it can be safely placed inside a URL query.
1query := url.QueryEscape("my/cool+blog&about,stuff")
2fmt.Println(query)
Output
my%2Fcool%2Bblog%26about%2Cstuff
func QueryUnescape
1func QueryUnescape(s string) (string, error)
QueryUnescape does the inverse transformation of QueryEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB. It returns an error if any % is not followed by two hexadecimal digits.
1escapedQuery := "my%2Fcool%2Bblog%26about%2Cstuff"
2query, err := url.QueryUnescape(escapedQuery)
3if err != nil {
4 log.Fatal(err)
5}
6fmt.Println(query)
Output
my/cool+blog&about,stuff
func Parse
1func Parse(rawURL string) (*URL, error)
Parse parses a raw url into a URL structure.
The url may be relative (a path, without a host) or absolute (starting with a scheme). Trying to parse a hostname and path without a scheme is invalid but may not necessarily return an error, due to parsing ambiguities.
func ParseRequestURI
1func ParseRequestURI(rawURL string) (*URL, error)
ParseRequestURI parses a raw url into a URL structure. It assumes that url was received in an HTTP request, so the url is interpreted only as an absolute URI or an absolute path. The string url is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)
func User
1func User(username string) *Userinfo
User returns a Userinfo containing the provided username and no password set.
func UserPassword
1func UserPassword(username, password string) *Userinfo
UserPassword returns a Userinfo containing the provided username and password.
This functionality should only be used with legacy web sites. RFC 2396 warns that interpreting Userinfo this way “is NOT RECOMMENDED, because the passing of authentication information in clear text (such as URI) has proven to be a security risk in almost every case where it has been used.”
func ParseQuery
1func ParseQuery(query string) (Values, error)
ParseQuery parses the URL-encoded query string and returns a map listing the values specified for each key. ParseQuery always returns a non-nil map containing all the valid query parameters found; err describes the first decoding error encountered, if any.
Query is expected to be a list of key=value settings separated by ampersands. A setting without an equals sign is interpreted as a key set to an empty value. Settings containing a non-URL-encoded semicolon are considered invalid.
1m, err := url.ParseQuery(`x=1&y=2&y=3`)
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Println(toJSON(m))
Output
{"x":["1"], "y":["2", "3"]}
Types
type Error
1type Error struct {
2 Op string
3 URL string
4 Err error
5}
Error reports an error and the operation and URL that caused it.
func Error
1func (e *Error) Error() string
func Temporary
1func (e *Error) Temporary() bool
func Timeout
1func (e *Error) Timeout() bool
func Unwrap
1func (e *Error) Unwrap() error
type URL
1type URL struct {
2 Scheme string
3 Opaque string // encoded opaque data
4 User *Userinfo // username and password information
5 Host string // host or host:port
6 Path string // path (relative paths may omit leading slash)
7 RawPath string // encoded path hint (see EscapedPath method)
8 OmitHost bool // do not emit empty host (authority)
9 ForceQuery bool // append a query ('?') even if RawQuery is empty
10 RawQuery string // encoded query values, without '?'
11 Fragment string // fragment for references, without '#'
12 RawFragment string // encoded fragment hint (see EscapedFragment method)
13}
A URL represents a parsed URL (technically, a URI reference).
The general form represented is:
[scheme:][//[userinfo@]host][/]path[?query][#fragment]
URLs that do not start with a slash after the scheme are interpreted as:
scheme:opaque[?query][#fragment]
Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. A consequence is that it is impossible to tell which slashes in the Path were slashes in the raw URL and which were %2f. This distinction is rarely important, but when it is, the code should use the EscapedPath method, which preserves the original encoding of Path.
The RawPath field is an optional field which is only set when the default encoding of Path is different from the escaped path. See the EscapedPath method for more details.
URL’s String method uses the EscapedPath method to obtain the path.
func EscapedFragment
1func (u *URL) EscapedFragment() string
EscapedFragment returns the escaped form of u.Fragment. In general there are multiple possible escaped forms of any fragment. EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. Otherwise EscapedFragment ignores u.RawFragment and computes an escaped form on its own. The String method uses EscapedFragment to construct its result. In general, code should call EscapedFragment instead of reading u.RawFragment directly.
1u, err := url.Parse("http://example.com/#x/y%2Fz")
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Println("Fragment:", u.Fragment)
6fmt.Println("RawFragment:", u.RawFragment)
7fmt.Println("EscapedFragment:", u.EscapedFragment())
Output
Fragment: x/y/z RawFragment: x/y%2Fz EscapedFragment: x/y%2Fz
func EscapedPath
1func (u *URL) EscapedPath() string
EscapedPath returns the escaped form of u.Path. In general there are multiple possible escaped forms of any path. EscapedPath returns u.RawPath when it is a valid escaping of u.Path. Otherwise EscapedPath ignores u.RawPath and computes an escaped form on its own. The String and RequestURI methods use EscapedPath to construct their results. In general, code should call EscapedPath instead of reading u.RawPath directly.
1u, err := url.Parse("http://example.com/x/y%2Fz")
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Println("Path:", u.Path)
6fmt.Println("RawPath:", u.RawPath)
7fmt.Println("EscapedPath:", u.EscapedPath())
Output
Path: /x/y/z RawPath: /x/y%2Fz EscapedPath: /x/y%2Fz
func Hostname
1func (u *URL) Hostname() string
Hostname returns u.Host, stripping any valid port number if present.
If the result is enclosed in square brackets, as literal IPv6 addresses are, the square brackets are removed from the result.
1u, err := url.Parse("https://example.org:8000/path")
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Println(u.Hostname())
6u, err = url.Parse("https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000")
7if err != nil {
8 log.Fatal(err)
9}
10fmt.Println(u.Hostname())
Output
example.org 2001:0db8:85a3:0000:0000:8a2e:0370:7334
func IsAbs
1func (u *URL) IsAbs() bool
IsAbs reports whether the URL is absolute. Absolute means that it has a non-empty scheme.
1u := url.URL{Host: "example.com", Path: "foo"}
2fmt.Println(u.IsAbs())
3u.Scheme = "http"
4fmt.Println(u.IsAbs())
Output
false true
func JoinPath
1func (u *URL) JoinPath(elem ...string) *URL
JoinPath returns a new URL with the provided path elements joined to any existing path and the resulting path cleaned of any ./ or ../ elements. Any sequences of multiple / characters will be reduced to a single /.
func MarshalBinary
1func (u *URL) MarshalBinary() (text []byte, err error)
1u, _ := url.Parse("https://example.org")
2b, err := u.MarshalBinary()
3if err != nil {
4 log.Fatal(err)
5}
6fmt.Printf("%s\n", b)
Output
https://example.org
func Parse
1func (u *URL) Parse(ref string) (*URL, error)
Parse parses a URL in the context of the receiver. The provided URL may be relative or absolute. Parse returns nil, err on parse failure, otherwise its return value is the same as ResolveReference.
1u, err := url.Parse("https://example.org")
2if err != nil {
3 log.Fatal(err)
4}
5rel, err := u.Parse("/foo")
6if err != nil {
7 log.Fatal(err)
8}
9fmt.Println(rel)
10_, err = u.Parse(":foo")
11if _, ok := err.(*url.Error); !ok {
12 log.Fatal(err)
13}
Output
https://example.org/foo
func Port
1func (u *URL) Port() string
Port returns the port part of u.Host, without the leading colon.
If u.Host doesn’t contain a valid numeric port, Port returns an empty string.
1u, err := url.Parse("https://example.org")
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Println(u.Port())
6u, err = url.Parse("https://example.org:8080")
7if err != nil {
8 log.Fatal(err)
9}
10fmt.Println(u.Port())
Output
8080
func Query
1func (u *URL) Query() Values
Query parses RawQuery and returns the corresponding values. It silently discards malformed value pairs. To check errors use ParseQuery.
1u, err := url.Parse("https://example.org/?a=1&a=2&b=&=3&&&&")
2if err != nil {
3 log.Fatal(err)
4}
5q := u.Query()
6fmt.Println(q["a"])
7fmt.Println(q.Get("b"))
8fmt.Println(q.Get(""))
Output
[1 2] 3
func Redacted
1func (u *URL) Redacted() string
Redacted is like String but replaces any password with "xxxxx". Only the password in u.URL is redacted.
1u := &url.URL{
2 Scheme: "https",
3 User: url.UserPassword("user", "password"),
4 Host: "example.com",
5 Path: "foo/bar",
6}
7fmt.Println(u.Redacted())
8u.User = url.UserPassword("me", "newerPassword")
9fmt.Println(u.Redacted())
Output
https://user:xxxxx@example.com/foo/bar https://me:xxxxx@example.com/foo/bar
func RequestURI
1func (u *URL) RequestURI() string
RequestURI returns the encoded path?query or opaque?query string that would be used in an HTTP request for u.
1u, err := url.Parse("https://example.org/path?foo=bar")
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Println(u.RequestURI())
Output
/path?foo=bar
func ResolveReference
1func (u *URL) ResolveReference(ref *URL) *URL
ResolveReference resolves a URI reference to an absolute URI from an absolute base URI u, per RFC 3986 Section 5.2. The URI reference may be relative or absolute. ResolveReference always returns a new URL instance, even if the returned URL is identical to either the base or reference. If ref is an absolute URL, then ResolveReference ignores base and returns a copy of ref.
1u, err := url.Parse("../../..//search?q=dotnet")
2if err != nil {
3 log.Fatal(err)
4}
5base, err := url.Parse("http://example.com/directory/")
6if err != nil {
7 log.Fatal(err)
8}
9fmt.Println(base.ResolveReference(u))
Output
http://example.com/search?q=dotnet
func String
1func (u *URL) String() string
String reassembles the URL into a valid URL string. The general form of the result is one of:
scheme:opaque?query#fragment
scheme://userinfo@host/path?query#fragment
If u.Opaque is non-empty, String uses the first form; otherwise it uses the second form. Any non-ASCII characters in host are escaped. To obtain the path, String uses u.EscapedPath().
In the second form, the following rules apply:
- if u.Scheme is empty, scheme: is omitted.
- if u.User is nil, userinfo@ is omitted.
- if u.Host is empty, host/ is omitted.
- if u.Scheme and u.Host are empty and u.User is nil, the entire scheme://userinfo@host/ is omitted.
- if u.Host is non-empty and u.Path begins with a /, the form host/path does not add its own /.
- if u.RawQuery is empty, ?query is omitted.
- if u.Fragment is empty, #fragment is omitted.
1u := &url.URL{
2 Scheme: "https",
3 User: url.UserPassword("me", "pass"),
4 Host: "example.com",
5 Path: "foo/bar",
6 RawQuery: "x=1&y=2",
7 Fragment: "anchor",
8}
9fmt.Println(u.String())
10u.Opaque = "opaque"
11fmt.Println(u.String())
Output
https://me:pass@example.com/foo/bar?x=1&y=2#anchor https:opaque?x=1&y=2#anchor
func UnmarshalBinary
1func (u *URL) UnmarshalBinary(text []byte) error
1u := &url.URL{}
2err := u.UnmarshalBinary([]byte("https://example.org/foo"))
3if err != nil {
4 log.Fatal(err)
5}
6fmt.Printf("%s\n", u)
Output
https://example.org/foo
type Values
1type Values map[string][]string
Values maps a string key to a list of values. It is typically used for query parameters and form values. Unlike in the http.Header map, the keys in a Values map are case-sensitive.
func Add
1func (v Values) Add(key, value string)
Add adds the value to key. It appends to any existing values associated with key.
1v := url.Values{}
2v.Add("cat sounds", "meow")
3v.Add("cat sounds", "mew")
4v.Add("cat sounds", "mau")
5fmt.Println(v["cat sounds"])
Output
[meow mew mau]
func Del
1func (v Values) Del(key string)
Del deletes the values associated with key.
1v := url.Values{}
2v.Add("cat sounds", "meow")
3v.Add("cat sounds", "mew")
4v.Add("cat sounds", "mau")
5fmt.Println(v["cat sounds"])
6
7v.Del("cat sounds")
8fmt.Println(v["cat sounds"])
Output
[meow mew mau] []
func Encode
1func (v Values) Encode() string
Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key.
1v := url.Values{}
2v.Add("cat sounds", "meow")
3v.Add("cat sounds", "mew/")
4v.Add("cat sounds", "mau$")
5fmt.Println(v.Encode())
Output
cat+sounds=meow&cat+sounds=mew%2F&cat+sounds=mau%24
func Get
1func (v Values) Get(key string) string
Get gets the first value associated with the given key. If there are no values associated with the key, Get returns the empty string. To access multiple values, use the map directly.
1v := url.Values{}
2v.Add("cat sounds", "meow")
3v.Add("cat sounds", "mew")
4v.Add("cat sounds", "mau")
5fmt.Printf("%q\n", v.Get("cat sounds"))
6fmt.Printf("%q\n", v.Get("dog sounds"))
Output
"meow" ""
func Has
1func (v Values) Has(key string) bool
Has checks whether a given key is set.
1v := url.Values{}
2v.Add("cat sounds", "meow")
3v.Add("cat sounds", "mew")
4v.Add("cat sounds", "mau")
5fmt.Println(v.Has("cat sounds"))
6fmt.Println(v.Has("dog sounds"))
Output
true false
func Set
1func (v Values) Set(key, value string)
Set sets the key to value. It replaces any existing values.
1v := url.Values{}
2v.Add("cat sounds", "meow")
3v.Add("cat sounds", "mew")
4v.Add("cat sounds", "mau")
5fmt.Println(v["cat sounds"])
6
7v.Set("cat sounds", "meow")
8fmt.Println(v["cat sounds"])
Output
[meow mew mau] [meow]