Movatterモバイル変換


[0]ホーム

URL:


url

packagestandard library
go1.25.4Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2025 License:BSD-3-ClauseImports:9Imported by:545,438

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package url parses URLs and implements query escaping.

SeeRFC 3986. This package generally followsRFC 3986, except whereit deviates for compatibility reasons.RFC 6874 followed for IPv6 zone literals.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcJoinPathadded ingo1.19

func JoinPath(basestring, elem ...string) (resultstring, errerror)

JoinPath returns aURL string with the provided path elements joined tothe existing path of base and the resulting path cleaned of any ./ or ../ elements.

funcPathEscapeadded ingo1.8

func PathEscape(sstring)string

PathEscape escapes the string so it can be safely placed inside aURL path segment,replacing special characters (including /) with %XX sequences as needed.

Example
package mainimport ("fmt""net/url")func main() {path := url.PathEscape("my/cool+blog&about,stuff")fmt.Println(path)}
Output:my%2Fcool+blog&about%2Cstuff

funcPathUnescapeadded ingo1.8

func PathUnescape(sstring) (string,error)

PathUnescape does the inverse transformation ofPathEscape,converting each 3-byte encoded substring of the form "%AB" into thehex-decoded byte 0xAB. It returns an error if any % is not followedby two hexadecimal digits.

PathUnescape is identical toQueryUnescape except that it does notunescape '+' to ' ' (space).

Example
package mainimport ("fmt""log""net/url")func main() {escapedPath := "my%2Fcool+blog&about%2Cstuff"path, err := url.PathUnescape(escapedPath)if err != nil {log.Fatal(err)}fmt.Println(path)}
Output:my/cool+blog&about,stuff

funcQueryEscape

func QueryEscape(sstring)string

QueryEscape escapes the string so it can be safely placedinside aURL query.

Example
package mainimport ("fmt""net/url")func main() {query := url.QueryEscape("my/cool+blog&about,stuff")fmt.Println(query)}
Output:my%2Fcool%2Bblog%26about%2Cstuff

funcQueryUnescape

func QueryUnescape(sstring) (string,error)

QueryUnescape does the inverse transformation ofQueryEscape,converting each 3-byte encoded substring of the form "%AB" into thehex-decoded byte 0xAB.It returns an error if any % is not followed by two hexadecimaldigits.

Example
package mainimport ("fmt""log""net/url")func main() {escapedQuery := "my%2Fcool%2Bblog%26about%2Cstuff"query, err := url.QueryUnescape(escapedQuery)if err != nil {log.Fatal(err)}fmt.Println(query)}
Output:my/cool+blog&about,stuff

Types

typeError

type Error struct {OpstringURLstringErrerror}

Error reports an error and the operation and URL that caused it.

func (*Error)Error

func (e *Error) Error()string

func (*Error)Temporaryadded ingo1.6

func (e *Error) Temporary()bool

func (*Error)Timeoutadded ingo1.6

func (e *Error) Timeout()bool

func (*Error)Unwrapadded ingo1.13

func (e *Error) Unwrap()error

typeEscapeError

type EscapeErrorstring

func (EscapeError)Error

func (eEscapeError) Error()string

typeInvalidHostErroradded ingo1.6

type InvalidHostErrorstring

func (InvalidHostError)Erroradded ingo1.6

func (eInvalidHostError) Error()string

typeURL

type URL struct {SchemestringOpaquestring// encoded opaque dataUser        *Userinfo// username and password informationHoststring// host or host:port (see Hostname and Port methods)Pathstring// path (relative paths may omit leading slash)RawPathstring// encoded path hint (see EscapedPath method)OmitHostbool// do not emit empty host (authority)ForceQuerybool// append a query ('?') even if RawQuery is emptyRawQuerystring// encoded query values, without '?'Fragmentstring// fragment for references, without '#'RawFragmentstring// encoded fragment hint (see EscapedFragment method)}

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]

The Host field contains the host and port subcomponents of the URL.When the port is present, it is separated from the host with a colon.When the host is an IPv6 address, it must be enclosed in square brackets:"[fe80::1]:80". Thenet.JoinHostPort function combines a host and portinto a string suitable for the Host field, adding square brackets tothe host when necessary.

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 wereslashes in the raw URL and which were %2f. This distinction is rarely important,but when it is, the code should use theURL.EscapedPath method, which preservesthe original encoding of Path.

The RawPath field is an optional field which is only set when the defaultencoding of Path is different from the escaped path. See the EscapedPath methodfor more details.

URL's String method uses the EscapedPath method to obtain the path.

Example
package mainimport ("fmt""log""net/url")func main() {u, err := url.Parse("http://bing.com/search?q=dotnet")if err != nil {log.Fatal(err)}u.Scheme = "https"u.Host = "google.com"q := u.Query()q.Set("q", "golang")u.RawQuery = q.Encode()fmt.Println(u)}
Output:https://google.com/search?q=golang

Example (Roundtrip)
package mainimport ("fmt""log""net/url")func main() {// 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%2fbarhttps://example.com/foo%2fbar

funcParse

func Parse(rawURLstring) (*URL,error)

Parse parses a raw url into aURL structure.

The url may be relative (a path, without a host) or absolute(starting with a scheme). Trying to parse a hostname and pathwithout a scheme is invalid but may not necessarily return anerror, due to parsing ambiguities.

funcParseRequestURI

func ParseRequestURI(rawURLstring) (*URL,error)

ParseRequestURI parses a raw url into aURL structure. It assumes thaturl was received in an HTTP request, so the url is interpretedonly 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 (*URL)AppendBinaryadded ingo1.24.0

func (u *URL) AppendBinary(b []byte) ([]byte,error)

func (*URL)EscapedFragmentadded ingo1.15

func (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 escapedform on its own.TheURL.String method uses EscapedFragment to construct its result.In general, code should call EscapedFragment instead ofreading u.RawFragment directly.

Example
package mainimport ("fmt""log""net/url")func main() {u, err := url.Parse("http://example.com/#x/y%2Fz")if err != nil {log.Fatal(err)}fmt.Println("Fragment:", u.Fragment)fmt.Println("RawFragment:", u.RawFragment)fmt.Println("EscapedFragment:", u.EscapedFragment())}
Output:Fragment: x/y/zRawFragment: x/y%2FzEscapedFragment: x/y%2Fz

func (*URL)EscapedPathadded ingo1.5

func (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 escapedform on its own.TheURL.String andURL.RequestURI methods use EscapedPath to constructtheir results.In general, code should call EscapedPath instead ofreading u.RawPath directly.

Example
package mainimport ("fmt""log""net/url")func main() {u, err := url.Parse("http://example.com/x/y%2Fz")if err != nil {log.Fatal(err)}fmt.Println("Path:", u.Path)fmt.Println("RawPath:", u.RawPath)fmt.Println("EscapedPath:", u.EscapedPath())}
Output:Path: /x/y/zRawPath: /x/y%2FzEscapedPath: /x/y%2Fz

func (*URL)Hostnameadded ingo1.8

func (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.

Example
package mainimport ("fmt""log""net/url")func main() {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.org2001:0db8:85a3:0000:0000:8a2e:0370:7334

func (*URL)IsAbs

func (u *URL) IsAbs()bool

IsAbs reports whether theURL is absolute.Absolute means that it has a non-empty scheme.

Example
package mainimport ("fmt""net/url")func main() {u := url.URL{Host: "example.com", Path: "foo"}fmt.Println(u.IsAbs())u.Scheme = "http"fmt.Println(u.IsAbs())}
Output:falsetrue

func (*URL)JoinPathadded ingo1.19

func (u *URL) JoinPath(elem ...string) *URL

JoinPath returns a newURL with the provided path elements joined toany existing path and the resulting path cleaned of any ./ or ../ elements.Any sequences of multiple / characters will be reduced to a single /.

Example
package mainimport ("fmt""log""net/url")func main() {u, err := url.Parse("https://example.com/foo/bar")if err != nil {log.Fatal(err)}fmt.Println(u.JoinPath("baz", "qux"))}
Output:https://example.com/foo/bar/baz/qux

func (*URL)MarshalBinaryadded ingo1.8

func (u *URL) MarshalBinary() (text []byte, errerror)
Example
package mainimport ("fmt""log""net/url")func main() {u, _ := url.Parse("https://example.org")b, err := u.MarshalBinary()if err != nil {log.Fatal(err)}fmt.Printf("%s\n", b)}
Output:https://example.org

func (*URL)Parse

func (u *URL) Parse(refstring) (*URL,error)

Parse parses aURL in the context of the receiver. The provided URLmay be relative or absolute. Parse returns nil, err on parsefailure, otherwise its return value is the same asURL.ResolveReference.

Example
package mainimport ("fmt""log""net/url")func main() {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)Portadded ingo1.8

func (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.

Example
package mainimport ("fmt""log""net/url")func main() {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()Values

Query parses RawQuery and returns the corresponding values.It silently discards malformed value pairs.To check errors useParseQuery.

Example
package mainimport ("fmt""log""net/url")func main() {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["a"])fmt.Println(q.Get("b"))fmt.Println(q.Get(""))}
Output:[1 2]3

func (*URL)Redactedadded ingo1.15

func (u *URL) Redacted()string

Redacted is likeURL.String but replaces any password with "xxxxx".Only the password in u.User is redacted.

Example
package mainimport ("fmt""net/url")func main() {u := &url.URL{Scheme: "https",User:   url.UserPassword("user", "password"),Host:   "example.com",Path:   "foo/bar",}fmt.Println(u.Redacted())u.User = url.UserPassword("me", "newerPassword")fmt.Println(u.Redacted())}
Output:https://user:xxxxx@example.com/foo/barhttps://me:xxxxx@example.com/foo/bar

func (*URL)RequestURI

func (u *URL) RequestURI()string

RequestURI returns the encoded path?query or opaque?querystring that would be used in an HTTP request for u.

Example
package mainimport ("fmt""log""net/url")func main() {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

func (u *URL) ResolveReference(ref *URL) *URL

ResolveReference resolves a URI reference to an absolute URI froman absolute base URI u, perRFC 3986 Section 5.2. The URI referencemay be relative or absolute. ResolveReference always returns a newURL instance, even if the returned URL is identical to either thebase or reference. If ref is an absolute URL, then ResolveReferenceignores base and returns a copy of ref.

Example
package mainimport ("fmt""log""net/url")func main() {u, err := url.Parse("../../..//search?q=dotnet")if err != nil {log.Fatal(err)}base, err := url.Parse("http://example.com/directory/")if err != nil {log.Fatal(err)}fmt.Println(base.ResolveReference(u))}
Output:http://example.com/search?q=dotnet

func (*URL)String

func (u *URL) String()string

String reassembles theURL into a valid URL string.The general form of the result is one of:

scheme:opaque?query#fragmentscheme://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.
Example
package mainimport ("fmt""net/url")func main() {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#anchorhttps:opaque?x=1&y=2#anchor

func (*URL)UnmarshalBinaryadded ingo1.8

func (u *URL) UnmarshalBinary(text []byte)error
Example
package mainimport ("fmt""log""net/url")func main() {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

typeUserinfo

type Userinfo struct {// contains filtered or unexported fields}

The Userinfo type is an immutable encapsulation of username andpassword details for aURL. An existing Userinfo value is guaranteedto have a username set (potentially empty, as allowed byRFC 2396),and optionally a password.

funcUser

func User(usernamestring) *Userinfo

User returns aUserinfo containing the provided usernameand no password set.

funcUserPassword

func UserPassword(username, passwordstring) *Userinfo

UserPassword returns aUserinfo containing the provided usernameand 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 authenticationinformation in clear text (such as URI) has proven to be asecurity risk in almost every case where it has been used.”

func (*Userinfo)Password

func (u *Userinfo) Password() (string,bool)

Password returns the password in case it is set, and whether it is set.

func (*Userinfo)String

func (u *Userinfo) String()string

String returns the encoded userinfo information in the standard formof "username[:password]".

func (*Userinfo)Username

func (u *Userinfo) Username()string

Username returns the username.

typeValues

type 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 mapare case-sensitive.

Example
package mainimport ("fmt""net/url")func main() {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:AvaJess[Jess Sarah Zoe]

funcParseQuery

func ParseQuery(querystring) (Values,error)

ParseQuery parses the URL-encoded query string and returnsa map listing the values specified for each key.ParseQuery always returns a non-nil map containing all thevalid query parameters found; err describes the first decoding errorencountered, 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 emptyvalue.Settings containing a non-URL-encoded semicolon are considered invalid.

Example
package mainimport ("encoding/json""fmt""log""net/url""strings")func main() {m, err := url.ParseQuery(`x=1&y=2&y=3`)if err != nil {log.Fatal(err)}fmt.Println(toJSON(m))}func toJSON(m any) string {js, err := json.Marshal(m)if err != nil {log.Fatal(err)}return strings.ReplaceAll(string(js), ",", ", ")}
Output:{"x":["1"], "y":["2", "3"]}

func (Values)Add

func (vValues) Add(key, valuestring)

Add adds the value to key. It appends to any existingvalues associated with key.

Example
package mainimport ("fmt""net/url")func main() {v := url.Values{}v.Add("cat sounds", "meow")v.Add("cat sounds", "mew")v.Add("cat sounds", "mau")fmt.Println(v["cat sounds"])}
Output:[meow mew mau]

func (Values)Del

func (vValues) Del(keystring)

Del deletes the values associated with key.

Example
package mainimport ("fmt""net/url")func main() {v := url.Values{}v.Add("cat sounds", "meow")v.Add("cat sounds", "mew")v.Add("cat sounds", "mau")fmt.Println(v["cat sounds"])v.Del("cat sounds")fmt.Println(v["cat sounds"])}
Output:[meow mew mau][]

func (Values)Encode

func (vValues) Encode()string

Encode encodes the values into “URL encoded” form("bar=baz&foo=quux") sorted by key.

Example
package mainimport ("fmt""net/url")func main() {v := url.Values{}v.Add("cat sounds", "meow")v.Add("cat sounds", "mew/")v.Add("cat sounds", "mau$")fmt.Println(v.Encode())}
Output:cat+sounds=meow&cat+sounds=mew%2F&cat+sounds=mau%24

func (Values)Get

func (vValues) Get(keystring)string

Get gets the first value associated with the given key.If there are no values associated with the key, Get returnsthe empty string. To access multiple values, use the mapdirectly.

Example
package mainimport ("fmt""net/url")func main() {v := url.Values{}v.Add("cat sounds", "meow")v.Add("cat sounds", "mew")v.Add("cat sounds", "mau")fmt.Printf("%q\n", v.Get("cat sounds"))fmt.Printf("%q\n", v.Get("dog sounds"))}
Output:"meow"""

func (Values)Hasadded ingo1.17

func (vValues) Has(keystring)bool

Has checks whether a given key is set.

Example
package mainimport ("fmt""net/url")func main() {v := url.Values{}v.Add("cat sounds", "meow")v.Add("cat sounds", "mew")v.Add("cat sounds", "mau")fmt.Println(v.Has("cat sounds"))fmt.Println(v.Has("dog sounds"))}
Output:truefalse

func (Values)Set

func (vValues) Set(key, valuestring)

Set sets the key to value. It replaces any existingvalues.

Example
package mainimport ("fmt""net/url")func main() {v := url.Values{}v.Add("cat sounds", "meow")v.Add("cat sounds", "mew")v.Add("cat sounds", "mau")fmt.Println(v["cat sounds"])v.Set("cat sounds", "meow")fmt.Println(v["cat sounds"])}
Output:[meow mew mau][meow]

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp