...
Run Format

Source file src/net/url/url.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	// Package url parses URLs and implements query escaping.
     6	// See RFC 3986.
     7	package url
     8	
     9	import (
    10		"bytes"
    11		"errors"
    12		"fmt"
    13		"sort"
    14		"strconv"
    15		"strings"
    16	)
    17	
    18	// Error reports an error and the operation and URL that caused it.
    19	type Error struct {
    20		Op  string
    21		URL string
    22		Err error
    23	}
    24	
    25	func (e *Error) Error() string { return e.Op + " " + e.URL + ": " + e.Err.Error() }
    26	
    27	type timeout interface {
    28		Timeout() bool
    29	}
    30	
    31	func (e *Error) Timeout() bool {
    32		t, ok := e.Err.(timeout)
    33		return ok && t.Timeout()
    34	}
    35	
    36	type temporary interface {
    37		Temporary() bool
    38	}
    39	
    40	func (e *Error) Temporary() bool {
    41		t, ok := e.Err.(temporary)
    42		return ok && t.Temporary()
    43	}
    44	
    45	func ishex(c byte) bool {
    46		switch {
    47		case '0' <= c && c <= '9':
    48			return true
    49		case 'a' <= c && c <= 'f':
    50			return true
    51		case 'A' <= c && c <= 'F':
    52			return true
    53		}
    54		return false
    55	}
    56	
    57	func unhex(c byte) byte {
    58		switch {
    59		case '0' <= c && c <= '9':
    60			return c - '0'
    61		case 'a' <= c && c <= 'f':
    62			return c - 'a' + 10
    63		case 'A' <= c && c <= 'F':
    64			return c - 'A' + 10
    65		}
    66		return 0
    67	}
    68	
    69	type encoding int
    70	
    71	const (
    72		encodePath encoding = 1 + iota
    73		encodeHost
    74		encodeZone
    75		encodeUserPassword
    76		encodeQueryComponent
    77		encodeFragment
    78	)
    79	
    80	type EscapeError string
    81	
    82	func (e EscapeError) Error() string {
    83		return "invalid URL escape " + strconv.Quote(string(e))
    84	}
    85	
    86	type InvalidHostError string
    87	
    88	func (e InvalidHostError) Error() string {
    89		return "invalid character " + strconv.Quote(string(e)) + " in host name"
    90	}
    91	
    92	// Return true if the specified character should be escaped when
    93	// appearing in a URL string, according to RFC 3986.
    94	//
    95	// Please be informed that for now shouldEscape does not check all
    96	// reserved characters correctly. See golang.org/issue/5684.
    97	func shouldEscape(c byte, mode encoding) bool {
    98		// §2.3 Unreserved characters (alphanum)
    99		if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
   100			return false
   101		}
   102	
   103		if mode == encodeHost || mode == encodeZone {
   104			// §3.2.2 Host allows
   105			//	sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
   106			// as part of reg-name.
   107			// We add : because we include :port as part of host.
   108			// We add [ ] because we include [ipv6]:port as part of host.
   109			// We add < > because they're the only characters left that
   110			// we could possibly allow, and Parse will reject them if we
   111			// escape them (because hosts can't use %-encoding for
   112			// ASCII bytes).
   113			switch c {
   114			case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"':
   115				return false
   116			}
   117		}
   118	
   119		switch c {
   120		case '-', '_', '.', '~': // §2.3 Unreserved characters (mark)
   121			return false
   122	
   123		case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved)
   124			// Different sections of the URL allow a few of
   125			// the reserved characters to appear unescaped.
   126			switch mode {
   127			case encodePath: // §3.3
   128				// The RFC allows : @ & = + $ but saves / ; , for assigning
   129				// meaning to individual path segments. This package
   130				// only manipulates the path as a whole, so we allow those
   131				// last two as well. That leaves only ? to escape.
   132				return c == '?'
   133	
   134			case encodeUserPassword: // §3.2.1
   135				// The RFC allows ';', ':', '&', '=', '+', '$', and ',' in
   136				// userinfo, so we must escape only '@', '/', and '?'.
   137				// The parsing of userinfo treats ':' as special so we must escape
   138				// that too.
   139				return c == '@' || c == '/' || c == '?' || c == ':'
   140	
   141			case encodeQueryComponent: // §3.4
   142				// The RFC reserves (so we must escape) everything.
   143				return true
   144	
   145			case encodeFragment: // §4.1
   146				// The RFC text is silent but the grammar allows
   147				// everything, so escape nothing.
   148				return false
   149			}
   150		}
   151	
   152		// Everything else must be escaped.
   153		return true
   154	}
   155	
   156	// QueryUnescape does the inverse transformation of QueryEscape, converting
   157	// %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if
   158	// any % is not followed by two hexadecimal digits.
   159	func QueryUnescape(s string) (string, error) {
   160		return unescape(s, encodeQueryComponent)
   161	}
   162	
   163	// unescape unescapes a string; the mode specifies
   164	// which section of the URL string is being unescaped.
   165	func unescape(s string, mode encoding) (string, error) {
   166		// Count %, check that they're well-formed.
   167		n := 0
   168		hasPlus := false
   169		for i := 0; i < len(s); {
   170			switch s[i] {
   171			case '%':
   172				n++
   173				if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
   174					s = s[i:]
   175					if len(s) > 3 {
   176						s = s[:3]
   177					}
   178					return "", EscapeError(s)
   179				}
   180				// Per https://tools.ietf.org/html/rfc3986#page-21
   181				// in the host component %-encoding can only be used
   182				// for non-ASCII bytes.
   183				// But https://tools.ietf.org/html/rfc6874#section-2
   184				// introduces %25 being allowed to escape a percent sign
   185				// in IPv6 scoped-address literals. Yay.
   186				if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" {
   187					return "", EscapeError(s[i : i+3])
   188				}
   189				if mode == encodeZone {
   190					// RFC 6874 says basically "anything goes" for zone identifiers
   191					// and that even non-ASCII can be redundantly escaped,
   192					// but it seems prudent to restrict %-escaped bytes here to those
   193					// that are valid host name bytes in their unescaped form.
   194					// That is, you can use escaping in the zone identifier but not
   195					// to introduce bytes you couldn't just write directly.
   196					// But Windows puts spaces here! Yay.
   197					v := unhex(s[i+1])<<4 | unhex(s[i+2])
   198					if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) {
   199						return "", EscapeError(s[i : i+3])
   200					}
   201				}
   202				i += 3
   203			case '+':
   204				hasPlus = mode == encodeQueryComponent
   205				i++
   206			default:
   207				if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
   208					return "", InvalidHostError(s[i : i+1])
   209				}
   210				i++
   211			}
   212		}
   213	
   214		if n == 0 && !hasPlus {
   215			return s, nil
   216		}
   217	
   218		t := make([]byte, len(s)-2*n)
   219		j := 0
   220		for i := 0; i < len(s); {
   221			switch s[i] {
   222			case '%':
   223				t[j] = unhex(s[i+1])<<4 | unhex(s[i+2])
   224				j++
   225				i += 3
   226			case '+':
   227				if mode == encodeQueryComponent {
   228					t[j] = ' '
   229				} else {
   230					t[j] = '+'
   231				}
   232				j++
   233				i++
   234			default:
   235				t[j] = s[i]
   236				j++
   237				i++
   238			}
   239		}
   240		return string(t), nil
   241	}
   242	
   243	// QueryEscape escapes the string so it can be safely placed
   244	// inside a URL query.
   245	func QueryEscape(s string) string {
   246		return escape(s, encodeQueryComponent)
   247	}
   248	
   249	func escape(s string, mode encoding) string {
   250		spaceCount, hexCount := 0, 0
   251		for i := 0; i < len(s); i++ {
   252			c := s[i]
   253			if shouldEscape(c, mode) {
   254				if c == ' ' && mode == encodeQueryComponent {
   255					spaceCount++
   256				} else {
   257					hexCount++
   258				}
   259			}
   260		}
   261	
   262		if spaceCount == 0 && hexCount == 0 {
   263			return s
   264		}
   265	
   266		t := make([]byte, len(s)+2*hexCount)
   267		j := 0
   268		for i := 0; i < len(s); i++ {
   269			switch c := s[i]; {
   270			case c == ' ' && mode == encodeQueryComponent:
   271				t[j] = '+'
   272				j++
   273			case shouldEscape(c, mode):
   274				t[j] = '%'
   275				t[j+1] = "0123456789ABCDEF"[c>>4]
   276				t[j+2] = "0123456789ABCDEF"[c&15]
   277				j += 3
   278			default:
   279				t[j] = s[i]
   280				j++
   281			}
   282		}
   283		return string(t)
   284	}
   285	
   286	// A URL represents a parsed URL (technically, a URI reference).
   287	// The general form represented is:
   288	//
   289	//	scheme://[userinfo@]host/path[?query][#fragment]
   290	//
   291	// URLs that do not start with a slash after the scheme are interpreted as:
   292	//
   293	//	scheme:opaque[?query][#fragment]
   294	//
   295	// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
   296	// A consequence is that it is impossible to tell which slashes in the Path were
   297	// slashes in the raw URL and which were %2f. This distinction is rarely important,
   298	// but when it is, code must not use Path directly.
   299	//
   300	// Go 1.5 introduced the RawPath field to hold the encoded form of Path.
   301	// The Parse function sets both Path and RawPath in the URL it returns,
   302	// and URL's String method uses RawPath if it is a valid encoding of Path,
   303	// by calling the EscapedPath method.
   304	//
   305	// In earlier versions of Go, the more indirect workarounds were that an
   306	// HTTP server could consult req.RequestURI and an HTTP client could
   307	// construct a URL struct directly and set the Opaque field instead of Path.
   308	// These still work as well.
   309	type URL struct {
   310		Scheme   string
   311		Opaque   string    // encoded opaque data
   312		User     *Userinfo // username and password information
   313		Host     string    // host or host:port
   314		Path     string
   315		RawPath  string // encoded path hint (Go 1.5 and later only; see EscapedPath method)
   316		RawQuery string // encoded query values, without '?'
   317		Fragment string // fragment for references, without '#'
   318	}
   319	
   320	// User returns a Userinfo containing the provided username
   321	// and no password set.
   322	func User(username string) *Userinfo {
   323		return &Userinfo{username, "", false}
   324	}
   325	
   326	// UserPassword returns a Userinfo containing the provided username
   327	// and password.
   328	// This functionality should only be used with legacy web sites.
   329	// RFC 2396 warns that interpreting Userinfo this way
   330	// ``is NOT RECOMMENDED, because the passing of authentication
   331	// information in clear text (such as URI) has proven to be a
   332	// security risk in almost every case where it has been used.''
   333	func UserPassword(username, password string) *Userinfo {
   334		return &Userinfo{username, password, true}
   335	}
   336	
   337	// The Userinfo type is an immutable encapsulation of username and
   338	// password details for a URL. An existing Userinfo value is guaranteed
   339	// to have a username set (potentially empty, as allowed by RFC 2396),
   340	// and optionally a password.
   341	type Userinfo struct {
   342		username    string
   343		password    string
   344		passwordSet bool
   345	}
   346	
   347	// Username returns the username.
   348	func (u *Userinfo) Username() string {
   349		return u.username
   350	}
   351	
   352	// Password returns the password in case it is set, and whether it is set.
   353	func (u *Userinfo) Password() (string, bool) {
   354		if u.passwordSet {
   355			return u.password, true
   356		}
   357		return "", false
   358	}
   359	
   360	// String returns the encoded userinfo information in the standard form
   361	// of "username[:password]".
   362	func (u *Userinfo) String() string {
   363		s := escape(u.username, encodeUserPassword)
   364		if u.passwordSet {
   365			s += ":" + escape(u.password, encodeUserPassword)
   366		}
   367		return s
   368	}
   369	
   370	// Maybe rawurl is of the form scheme:path.
   371	// (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
   372	// If so, return scheme, path; else return "", rawurl.
   373	func getscheme(rawurl string) (scheme, path string, err error) {
   374		for i := 0; i < len(rawurl); i++ {
   375			c := rawurl[i]
   376			switch {
   377			case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
   378			// do nothing
   379			case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.':
   380				if i == 0 {
   381					return "", rawurl, nil
   382				}
   383			case c == ':':
   384				if i == 0 {
   385					return "", "", errors.New("missing protocol scheme")
   386				}
   387				return rawurl[:i], rawurl[i+1:], nil
   388			default:
   389				// we have encountered an invalid character,
   390				// so there is no valid scheme
   391				return "", rawurl, nil
   392			}
   393		}
   394		return "", rawurl, nil
   395	}
   396	
   397	// Maybe s is of the form t c u.
   398	// If so, return t, c u (or t, u if cutc == true).
   399	// If not, return s, "".
   400	func split(s string, c string, cutc bool) (string, string) {
   401		i := strings.Index(s, c)
   402		if i < 0 {
   403			return s, ""
   404		}
   405		if cutc {
   406			return s[:i], s[i+len(c):]
   407		}
   408		return s[:i], s[i:]
   409	}
   410	
   411	// Parse parses rawurl into a URL structure.
   412	// The rawurl may be relative or absolute.
   413	func Parse(rawurl string) (url *URL, err error) {
   414		// Cut off #frag
   415		u, frag := split(rawurl, "#", true)
   416		if url, err = parse(u, false); err != nil {
   417			return nil, err
   418		}
   419		if frag == "" {
   420			return url, nil
   421		}
   422		if url.Fragment, err = unescape(frag, encodeFragment); err != nil {
   423			return nil, &Error{"parse", rawurl, err}
   424		}
   425		return url, nil
   426	}
   427	
   428	// ParseRequestURI parses rawurl into a URL structure.  It assumes that
   429	// rawurl was received in an HTTP request, so the rawurl is interpreted
   430	// only as an absolute URI or an absolute path.
   431	// The string rawurl is assumed not to have a #fragment suffix.
   432	// (Web browsers strip #fragment before sending the URL to a web server.)
   433	func ParseRequestURI(rawurl string) (url *URL, err error) {
   434		return parse(rawurl, true)
   435	}
   436	
   437	// parse parses a URL from a string in one of two contexts.  If
   438	// viaRequest is true, the URL is assumed to have arrived via an HTTP request,
   439	// in which case only absolute URLs or path-absolute relative URLs are allowed.
   440	// If viaRequest is false, all forms of relative URLs are allowed.
   441	func parse(rawurl string, viaRequest bool) (url *URL, err error) {
   442		var rest string
   443	
   444		if rawurl == "" && viaRequest {
   445			err = errors.New("empty url")
   446			goto Error
   447		}
   448		url = new(URL)
   449	
   450		if rawurl == "*" {
   451			url.Path = "*"
   452			return
   453		}
   454	
   455		// Split off possible leading "http:", "mailto:", etc.
   456		// Cannot contain escaped characters.
   457		if url.Scheme, rest, err = getscheme(rawurl); err != nil {
   458			goto Error
   459		}
   460		url.Scheme = strings.ToLower(url.Scheme)
   461	
   462		rest, url.RawQuery = split(rest, "?", true)
   463	
   464		if !strings.HasPrefix(rest, "/") {
   465			if url.Scheme != "" {
   466				// We consider rootless paths per RFC 3986 as opaque.
   467				url.Opaque = rest
   468				return url, nil
   469			}
   470			if viaRequest {
   471				err = errors.New("invalid URI for request")
   472				goto Error
   473			}
   474		}
   475	
   476		if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
   477			var authority string
   478			authority, rest = split(rest[2:], "/", false)
   479			url.User, url.Host, err = parseAuthority(authority)
   480			if err != nil {
   481				goto Error
   482			}
   483		}
   484		if url.Path, err = unescape(rest, encodePath); err != nil {
   485			goto Error
   486		}
   487		// RawPath is a hint as to the encoding of Path to use
   488		// in url.EscapedPath. If that method already gets the
   489		// right answer without RawPath, leave it empty.
   490		// This will help make sure that people don't rely on it in general.
   491		if url.EscapedPath() != rest && validEncodedPath(rest) {
   492			url.RawPath = rest
   493		}
   494		return url, nil
   495	
   496	Error:
   497		return nil, &Error{"parse", rawurl, err}
   498	}
   499	
   500	func parseAuthority(authority string) (user *Userinfo, host string, err error) {
   501		i := strings.LastIndex(authority, "@")
   502		if i < 0 {
   503			host, err = parseHost(authority)
   504		} else {
   505			host, err = parseHost(authority[i+1:])
   506		}
   507		if err != nil {
   508			return nil, "", err
   509		}
   510		if i < 0 {
   511			return nil, host, nil
   512		}
   513		userinfo := authority[:i]
   514		if strings.Index(userinfo, ":") < 0 {
   515			if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
   516				return nil, "", err
   517			}
   518			user = User(userinfo)
   519		} else {
   520			username, password := split(userinfo, ":", true)
   521			if username, err = unescape(username, encodeUserPassword); err != nil {
   522				return nil, "", err
   523			}
   524			if password, err = unescape(password, encodeUserPassword); err != nil {
   525				return nil, "", err
   526			}
   527			user = UserPassword(username, password)
   528		}
   529		return user, host, nil
   530	}
   531	
   532	// parseHost parses host as an authority without user
   533	// information. That is, as host[:port].
   534	func parseHost(host string) (string, error) {
   535		if strings.HasPrefix(host, "[") {
   536			// Parse an IP-Literal in RFC 3986 and RFC 6874.
   537			// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
   538			i := strings.LastIndex(host, "]")
   539			if i < 0 {
   540				return "", errors.New("missing ']' in host")
   541			}
   542			colonPort := host[i+1:]
   543			if !validOptionalPort(colonPort) {
   544				return "", fmt.Errorf("invalid port %q after host", colonPort)
   545			}
   546	
   547			// RFC 6874 defines that %25 (%-encoded percent) introduces
   548			// the zone identifier, and the zone identifier can use basically
   549			// any %-encoding it likes. That's different from the host, which
   550			// can only %-encode non-ASCII bytes.
   551			// We do impose some restrictions on the zone, to avoid stupidity
   552			// like newlines.
   553			zone := strings.Index(host[:i], "%25")
   554			if zone >= 0 {
   555				host1, err := unescape(host[:zone], encodeHost)
   556				if err != nil {
   557					return "", err
   558				}
   559				host2, err := unescape(host[zone:i], encodeZone)
   560				if err != nil {
   561					return "", err
   562				}
   563				host3, err := unescape(host[i:], encodeHost)
   564				if err != nil {
   565					return "", err
   566				}
   567				return host1 + host2 + host3, nil
   568			}
   569		}
   570	
   571		var err error
   572		if host, err = unescape(host, encodeHost); err != nil {
   573			return "", err
   574		}
   575		return host, nil
   576	}
   577	
   578	// EscapedPath returns the escaped form of u.Path.
   579	// In general there are multiple possible escaped forms of any path.
   580	// EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
   581	// Otherwise EscapedPath ignores u.RawPath and computes an escaped
   582	// form on its own.
   583	// The String and RequestURI methods use EscapedPath to construct
   584	// their results.
   585	// In general, code should call EscapedPath instead of
   586	// reading u.RawPath directly.
   587	func (u *URL) EscapedPath() string {
   588		if u.RawPath != "" && validEncodedPath(u.RawPath) {
   589			p, err := unescape(u.RawPath, encodePath)
   590			if err == nil && p == u.Path {
   591				return u.RawPath
   592			}
   593		}
   594		if u.Path == "*" {
   595			return "*" // don't escape (Issue 11202)
   596		}
   597		return escape(u.Path, encodePath)
   598	}
   599	
   600	// validEncodedPath reports whether s is a valid encoded path.
   601	// It must not contain any bytes that require escaping during path encoding.
   602	func validEncodedPath(s string) bool {
   603		for i := 0; i < len(s); i++ {
   604			// RFC 3986, Appendix A.
   605			// pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
   606			// shouldEscape is not quite compliant with the RFC,
   607			// so we check the sub-delims ourselves and let
   608			// shouldEscape handle the others.
   609			switch s[i] {
   610			case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
   611				// ok
   612			case '[', ']':
   613				// ok - not specified in RFC 3986 but left alone by modern browsers
   614			case '%':
   615				// ok - percent encoded, will decode
   616			default:
   617				if shouldEscape(s[i], encodePath) {
   618					return false
   619				}
   620			}
   621		}
   622		return true
   623	}
   624	
   625	// validOptionalPort reports whether port is either an empty string
   626	// or matches /^:\d*$/
   627	func validOptionalPort(port string) bool {
   628		if port == "" {
   629			return true
   630		}
   631		if port[0] != ':' {
   632			return false
   633		}
   634		for _, b := range port[1:] {
   635			if b < '0' || b > '9' {
   636				return false
   637			}
   638		}
   639		return true
   640	}
   641	
   642	// String reassembles the URL into a valid URL string.
   643	// The general form of the result is one of:
   644	//
   645	//	scheme:opaque?query#fragment
   646	//	scheme://userinfo@host/path?query#fragment
   647	//
   648	// If u.Opaque is non-empty, String uses the first form;
   649	// otherwise it uses the second form.
   650	// To obtain the path, String uses u.EscapedPath().
   651	//
   652	// In the second form, the following rules apply:
   653	//	- if u.Scheme is empty, scheme: is omitted.
   654	//	- if u.User is nil, userinfo@ is omitted.
   655	//	- if u.Host is empty, host/ is omitted.
   656	//	- if u.Scheme and u.Host are empty and u.User is nil,
   657	//	   the entire scheme://userinfo@host/ is omitted.
   658	//	- if u.Host is non-empty and u.Path begins with a /,
   659	//	   the form host/path does not add its own /.
   660	//	- if u.RawQuery is empty, ?query is omitted.
   661	//	- if u.Fragment is empty, #fragment is omitted.
   662	func (u *URL) String() string {
   663		var buf bytes.Buffer
   664		if u.Scheme != "" {
   665			buf.WriteString(u.Scheme)
   666			buf.WriteByte(':')
   667		}
   668		if u.Opaque != "" {
   669			buf.WriteString(u.Opaque)
   670		} else {
   671			if u.Scheme != "" || u.Host != "" || u.User != nil {
   672				buf.WriteString("//")
   673				if ui := u.User; ui != nil {
   674					buf.WriteString(ui.String())
   675					buf.WriteByte('@')
   676				}
   677				if h := u.Host; h != "" {
   678					buf.WriteString(escape(h, encodeHost))
   679				}
   680			}
   681			path := u.EscapedPath()
   682			if path != "" && path[0] != '/' && u.Host != "" {
   683				buf.WriteByte('/')
   684			}
   685			buf.WriteString(path)
   686		}
   687		if u.RawQuery != "" {
   688			buf.WriteByte('?')
   689			buf.WriteString(u.RawQuery)
   690		}
   691		if u.Fragment != "" {
   692			buf.WriteByte('#')
   693			buf.WriteString(escape(u.Fragment, encodeFragment))
   694		}
   695		return buf.String()
   696	}
   697	
   698	// Values maps a string key to a list of values.
   699	// It is typically used for query parameters and form values.
   700	// Unlike in the http.Header map, the keys in a Values map
   701	// are case-sensitive.
   702	type Values map[string][]string
   703	
   704	// Get gets the first value associated with the given key.
   705	// If there are no values associated with the key, Get returns
   706	// the empty string. To access multiple values, use the map
   707	// directly.
   708	func (v Values) Get(key string) string {
   709		if v == nil {
   710			return ""
   711		}
   712		vs, ok := v[key]
   713		if !ok || len(vs) == 0 {
   714			return ""
   715		}
   716		return vs[0]
   717	}
   718	
   719	// Set sets the key to value. It replaces any existing
   720	// values.
   721	func (v Values) Set(key, value string) {
   722		v[key] = []string{value}
   723	}
   724	
   725	// Add adds the value to key. It appends to any existing
   726	// values associated with key.
   727	func (v Values) Add(key, value string) {
   728		v[key] = append(v[key], value)
   729	}
   730	
   731	// Del deletes the values associated with key.
   732	func (v Values) Del(key string) {
   733		delete(v, key)
   734	}
   735	
   736	// ParseQuery parses the URL-encoded query string and returns
   737	// a map listing the values specified for each key.
   738	// ParseQuery always returns a non-nil map containing all the
   739	// valid query parameters found; err describes the first decoding error
   740	// encountered, if any.
   741	func ParseQuery(query string) (m Values, err error) {
   742		m = make(Values)
   743		err = parseQuery(m, query)
   744		return
   745	}
   746	
   747	func parseQuery(m Values, query string) (err error) {
   748		for query != "" {
   749			key := query
   750			if i := strings.IndexAny(key, "&;"); i >= 0 {
   751				key, query = key[:i], key[i+1:]
   752			} else {
   753				query = ""
   754			}
   755			if key == "" {
   756				continue
   757			}
   758			value := ""
   759			if i := strings.Index(key, "="); i >= 0 {
   760				key, value = key[:i], key[i+1:]
   761			}
   762			key, err1 := QueryUnescape(key)
   763			if err1 != nil {
   764				if err == nil {
   765					err = err1
   766				}
   767				continue
   768			}
   769			value, err1 = QueryUnescape(value)
   770			if err1 != nil {
   771				if err == nil {
   772					err = err1
   773				}
   774				continue
   775			}
   776			m[key] = append(m[key], value)
   777		}
   778		return err
   779	}
   780	
   781	// Encode encodes the values into ``URL encoded'' form
   782	// ("bar=baz&foo=quux") sorted by key.
   783	func (v Values) Encode() string {
   784		if v == nil {
   785			return ""
   786		}
   787		var buf bytes.Buffer
   788		keys := make([]string, 0, len(v))
   789		for k := range v {
   790			keys = append(keys, k)
   791		}
   792		sort.Strings(keys)
   793		for _, k := range keys {
   794			vs := v[k]
   795			prefix := QueryEscape(k) + "="
   796			for _, v := range vs {
   797				if buf.Len() > 0 {
   798					buf.WriteByte('&')
   799				}
   800				buf.WriteString(prefix)
   801				buf.WriteString(QueryEscape(v))
   802			}
   803		}
   804		return buf.String()
   805	}
   806	
   807	// resolvePath applies special path segments from refs and applies
   808	// them to base, per RFC 3986.
   809	func resolvePath(base, ref string) string {
   810		var full string
   811		if ref == "" {
   812			full = base
   813		} else if ref[0] != '/' {
   814			i := strings.LastIndex(base, "/")
   815			full = base[:i+1] + ref
   816		} else {
   817			full = ref
   818		}
   819		if full == "" {
   820			return ""
   821		}
   822		var dst []string
   823		src := strings.Split(full, "/")
   824		for _, elem := range src {
   825			switch elem {
   826			case ".":
   827				// drop
   828			case "..":
   829				if len(dst) > 0 {
   830					dst = dst[:len(dst)-1]
   831				}
   832			default:
   833				dst = append(dst, elem)
   834			}
   835		}
   836		if last := src[len(src)-1]; last == "." || last == ".." {
   837			// Add final slash to the joined path.
   838			dst = append(dst, "")
   839		}
   840		return "/" + strings.TrimLeft(strings.Join(dst, "/"), "/")
   841	}
   842	
   843	// IsAbs reports whether the URL is absolute.
   844	func (u *URL) IsAbs() bool {
   845		return u.Scheme != ""
   846	}
   847	
   848	// Parse parses a URL in the context of the receiver.  The provided URL
   849	// may be relative or absolute.  Parse returns nil, err on parse
   850	// failure, otherwise its return value is the same as ResolveReference.
   851	func (u *URL) Parse(ref string) (*URL, error) {
   852		refurl, err := Parse(ref)
   853		if err != nil {
   854			return nil, err
   855		}
   856		return u.ResolveReference(refurl), nil
   857	}
   858	
   859	// ResolveReference resolves a URI reference to an absolute URI from
   860	// an absolute base URI, per RFC 3986 Section 5.2.  The URI reference
   861	// may be relative or absolute.  ResolveReference always returns a new
   862	// URL instance, even if the returned URL is identical to either the
   863	// base or reference. If ref is an absolute URL, then ResolveReference
   864	// ignores base and returns a copy of ref.
   865	func (u *URL) ResolveReference(ref *URL) *URL {
   866		url := *ref
   867		if ref.Scheme == "" {
   868			url.Scheme = u.Scheme
   869		}
   870		if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
   871			// The "absoluteURI" or "net_path" cases.
   872			url.Path = resolvePath(ref.Path, "")
   873			return &url
   874		}
   875		if ref.Opaque != "" {
   876			url.User = nil
   877			url.Host = ""
   878			url.Path = ""
   879			return &url
   880		}
   881		if ref.Path == "" {
   882			if ref.RawQuery == "" {
   883				url.RawQuery = u.RawQuery
   884				if ref.Fragment == "" {
   885					url.Fragment = u.Fragment
   886				}
   887			}
   888		}
   889		// The "abs_path" or "rel_path" cases.
   890		url.Host = u.Host
   891		url.User = u.User
   892		url.Path = resolvePath(u.Path, ref.Path)
   893		return &url
   894	}
   895	
   896	// Query parses RawQuery and returns the corresponding values.
   897	func (u *URL) Query() Values {
   898		v, _ := ParseQuery(u.RawQuery)
   899		return v
   900	}
   901	
   902	// RequestURI returns the encoded path?query or opaque?query
   903	// string that would be used in an HTTP request for u.
   904	func (u *URL) RequestURI() string {
   905		result := u.Opaque
   906		if result == "" {
   907			result = u.EscapedPath()
   908			if result == "" {
   909				result = "/"
   910			}
   911		} else {
   912			if strings.HasPrefix(result, "//") {
   913				result = u.Scheme + ":" + result
   914			}
   915		}
   916		if u.RawQuery != "" {
   917			result += "?" + u.RawQuery
   918		}
   919		return result
   920	}
   921	

View as plain text