Overview
Package url parses URLs and implements query escaping.
Index
Package files
func
¶
PathEscape escapes the string so it can be safely placed inside a URL path
segment.
- func PathUnescape(s ) (string, )
PathUnescape does the inverse transformation of PathEscape, converting each
3-byte encoded substring of the form “%AB” into the hex-decoded byte 0xAB. It
also converts ‘+’ into ‘ ‘ (space). It returns an error if any % is not followed
by two hexadecimal digits.
PathUnescape is identical to QueryUnescape except that it does not unescape ‘+’
to ‘ ‘ (space).
func QueryEscape
- func QueryEscape(s string)
QueryEscape escapes the string so it can be safely placed inside a URL query.
func QueryUnescape
QueryUnescape does the inverse transformation of QueryEscape, converting each
3-byte encoded substring of the form “%AB” into the hex-decoded byte 0xAB. It
also converts ‘+’ into ‘ ‘ (space). It returns an error if any % is not followed
by two hexadecimal digits.
type
¶
- type Error struct {
- Op
- URL string
- Err
- }
Error reports an error and the operation and URL that caused it.
func (*Error) Error
- func (e *Error) Error()
func (*Error) Temporary
- func (e *Error) Temporary()
func (*Error) Timeout
- func (e *Error) Timeout()
- type EscapeError string
func (EscapeError)
¶
- func (e ) Error() string
type
¶
- type InvalidHostError
func (InvalidHostError) Error
- func (e InvalidHostError) Error()
type URL
- type URL struct {
- Scheme string
- Opaque // encoded opaque data
- User *Userinfo // username and password information
- Host // host or host:port
- Path string // path (relative paths may omit leading slash)
- RawPath // encoded path hint (see EscapedPath method)
- ForceQuery bool // append a query ('?') even if RawQuery is empty
- RawQuery // encoded query values, without '?'
- Fragment string // fragment for references, without '#'
- }
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, code must not use Path directly. The Parse function sets both
Path and RawPath in the URL it returns, and URL’s String method uses RawPath if
it is a valid encoding of Path, by calling the EscapedPath method.
Example:
u, err := url.Parse("http://bing.com/search?q=dotnet")
if err != nil {
log.Fatal(err)
}
u.Scheme = "https"
u.Host = "google.com"
q.Set("q", "golang")
u.RawQuery = q.Encode()
fmt.Println(u)
// Output: https://google.com/search?q=golang
// Parse + String preserve the original encoding.
u, err := url.Parse("https://example.com/foo%2fbar")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Path)
fmt.Println(u.RawPath)
fmt.Println(u.String())
// Output:
// /foo/bar
// /foo%2fbar
// https://example.com/foo%2fbar
func
¶
- func Parse(rawurl ) (*URL, )
Parse parses rawurl into a URL structure.
func ParseRequestURI
ParseRequestURI parses rawurl into a URL structure. It assumes that rawurl was
received in an HTTP request, so the rawurl is interpreted only as an absolute
URI or an absolute path. The string rawurl is assumed not to have a #fragment
suffix. (Web browsers strip #fragment before sending the URL to a web server.)
func (*URL)
¶
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.
Example:
u, err := url.Parse("http://example.com/path with spaces")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.EscapedPath())
// Output:
// /path%20with%20spaces
- func (u *URL) Hostname()
Hostname returns u.Host, without any port number.
If Host is an IPv6 literal with a port number, Hostname returns the IPv6 literal
without the square brackets. IPv6 literals may include a zone identifier.
u, err := url.Parse("https://example.org:8000/path")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Hostname())
u, err = url.Parse("https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Hostname())
// Output:
// example.org
// 2001:0db8:85a3:0000:0000:8a2e:0370:7334
func (*URL)
¶
- func (u *) IsAbs() bool
IsAbs reports whether the URL is absolute. Absolute means that it has a
non-empty scheme.
Example:
u := url.URL{Host: "example.com", Path: "foo"}
fmt.Println(u.IsAbs())
u.Scheme = "http"
fmt.Println(u.IsAbs())
// Output:
// false
// true
func (*URL) MarshalBinary
Example:
u, _ := url.Parse("https://example.org")
b, err := u.MarshalBinary()
if err != nil {
}
fmt.Printf("%s\n", b)
// Output:
// https://example.org
func (*URL) Parse
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.
u, err := url.Parse("https://example.org")
if err != nil {
log.Fatal(err)
}
rel, err := u.Parse("/foo")
if err != nil {
log.Fatal(err)
}
fmt.Println(rel)
_, err = u.Parse(":foo")
if _, ok := err.(*url.Error); !ok {
log.Fatal(err)
}
// Output:
// https://example.org/foo
func (*URL)
¶
- func (u *) Port() string
Port returns the port part of u.Host, without the leading colon. If u.Host
doesn’t contain a port, Port returns an empty string.
Example:
u, err := url.Parse("https://example.org")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Port())
u, err = url.Parse("https://example.org:8080")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Port())
// Output:
//
// 8080
func (*URL) Query
- func (u *URL) Query()
Query parses RawQuery and returns the corresponding values. It silently discards
malformed value pairs. To check errors use ParseQuery.
u, err := url.Parse("https://example.org/?a=1&a=2&b=&=3&&&&")
if err != nil {
log.Fatal(err)
}
q := u.Query()
fmt.Println(q.Get("b"))
fmt.Println(q.Get(""))
// Output:
// [1 2]
//
// 3
func (*URL)
¶
- func (u *) RequestURI() string
RequestURI returns the encoded path?query or opaque?query string that would be
used in an HTTP request for u.
Example:
u, err := url.Parse("https://example.org/path?foo=bar")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.RequestURI())
// Output: /path?foo=bar
func (*URL) ResolveReference
ResolveReference resolves a URI reference to an absolute URI from an absolute
base URI, 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.
Example:
u, err := url.Parse("../../..//search?q=dotnet")
if err != nil {
log.Fatal(err)
}
base, err := url.Parse("http://example.com/directory/")
log.Fatal(err)
}
fmt.Println(base.ResolveReference(u))
// Output:
// http://example.com/search?q=dotnet
func (*URL) String
- func (u *URL) String()
String reassembles the URL into a valid URL string. The general form of the
result is one of:
If u.Opaque is non-empty, String uses the first form; otherwise it uses the
second form. 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.
u := &url.URL{
Scheme: "https",
User: url.UserPassword("me", "pass"),
Host: "example.com",
Path: "foo/bar",
RawQuery: "x=1&y=2",
Fragment: "anchor",
}
fmt.Println(u.String())
u.Opaque = "opaque"
fmt.Println(u.String())
// Output:
// https://me:pass@example.com/foo/bar?x=1&y=2#anchor
// https:opaque?x=1&y=2#anchor
func (*URL) UnmarshalBinary
Example:
u := &url.URL{}
err := u.UnmarshalBinary([]byte("https://example.org/foo"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", u)
// Output:
// https://example.org/foo
type Userinfo
- type Userinfo struct {
- // contains filtered or unexported fields
- }
The Userinfo type is an immutable encapsulation of username and password details
for a URL. An existing Userinfo value is guaranteed to have a username set
(potentially empty, as allowed by RFC 2396), and optionally a password.
- func User(username string) *
User returns a Userinfo containing the provided username and no password set.
func UserPassword
- func UserPassword(username, password string) *
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 (*Userinfo) Password
Password returns the password in case it is set, and whether it is set.
func (*Userinfo)
¶
- func (u *) String() string
String returns the encoded userinfo information in the standard form of
“username[:password]”.
func (*Userinfo)
¶
- func (u *) Username() string
Username returns the username.
- type Values map[][]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.
Example:
v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
v.Add("friend", "Sarah")
v.Add("friend", "Zoe")
// v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
fmt.Println(v.Get("name"))
fmt.Println(v.Get("friend"))
fmt.Println(v["friend"])
// Output:
// Ava
// Jess
// [Jess Sarah Zoe]
func ParseQuery
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 or
semicolons. A setting without an equals sign is interpreted as a key set to an
empty value.
Example:
m, err := url.ParseQuery(`x=1&y=2&y=3;z`)
if err != nil {
log.Fatal(err)
}
fmt.Println(toJSON(m))
// Output:
func (Values) Add
- func (v Values) Add(key, value )
Add adds the value to key. It appends to any existing values associated with
key.
func (Values) Del
- func (v Values) Del(key )
Del deletes the values associated with key.
func (Values) Encode
- func (v Values) Encode()
Encode encodes the values into ``URL encoded’’ form (“bar=baz&foo=quux”) sorted
by key.
func (Values) Get
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.
Set sets the key to value. It replaces any existing values.