...

Source file src/net/url/url.go

Documentation: net/url

     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  package url
     7  
     8  // See RFC 3986. This package generally follows RFC 3986, except where
     9  // it deviates for compatibility reasons. When sending changes, first
    10  // search old issues for history on decisions. Unit tests should also
    11  // contain references to issue numbers with details.
    12  
    13  import (
    14  	"errors"
    15  	"fmt"
    16  	"maps"
    17  	"net/netip"
    18  	"path"
    19  	"slices"
    20  	"strconv"
    21  	"strings"
    22  	_ "unsafe" // for linkname
    23  )
    24  
    25  // Error reports an error and the operation and URL that caused it.
    26  type Error struct {
    27  	Op  string
    28  	URL string
    29  	Err error
    30  }
    31  
    32  func (e *Error) Unwrap() error { return e.Err }
    33  func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) }
    34  
    35  func (e *Error) Timeout() bool {
    36  	t, ok := e.Err.(interface {
    37  		Timeout() bool
    38  	})
    39  	return ok && t.Timeout()
    40  }
    41  
    42  func (e *Error) Temporary() bool {
    43  	t, ok := e.Err.(interface {
    44  		Temporary() bool
    45  	})
    46  	return ok && t.Temporary()
    47  }
    48  
    49  const upperhex = "0123456789ABCDEF"
    50  
    51  func ishex(c byte) bool {
    52  	switch {
    53  	case '0' <= c && c <= '9':
    54  		return true
    55  	case 'a' <= c && c <= 'f':
    56  		return true
    57  	case 'A' <= c && c <= 'F':
    58  		return true
    59  	}
    60  	return false
    61  }
    62  
    63  func unhex(c byte) byte {
    64  	switch {
    65  	case '0' <= c && c <= '9':
    66  		return c - '0'
    67  	case 'a' <= c && c <= 'f':
    68  		return c - 'a' + 10
    69  	case 'A' <= c && c <= 'F':
    70  		return c - 'A' + 10
    71  	}
    72  	return 0
    73  }
    74  
    75  type encoding int
    76  
    77  const (
    78  	encodePath encoding = 1 + iota
    79  	encodePathSegment
    80  	encodeHost
    81  	encodeZone
    82  	encodeUserPassword
    83  	encodeQueryComponent
    84  	encodeFragment
    85  )
    86  
    87  type EscapeError string
    88  
    89  func (e EscapeError) Error() string {
    90  	return "invalid URL escape " + strconv.Quote(string(e))
    91  }
    92  
    93  type InvalidHostError string
    94  
    95  func (e InvalidHostError) Error() string {
    96  	return "invalid character " + strconv.Quote(string(e)) + " in host name"
    97  }
    98  
    99  // Return true if the specified character should be escaped when
   100  // appearing in a URL string, according to RFC 3986.
   101  //
   102  // Please be informed that for now shouldEscape does not check all
   103  // reserved characters correctly. See golang.org/issue/5684.
   104  func shouldEscape(c byte, mode encoding) bool {
   105  	// §2.3 Unreserved characters (alphanum)
   106  	if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
   107  		return false
   108  	}
   109  
   110  	if mode == encodeHost || mode == encodeZone {
   111  		// §3.2.2 Host allows
   112  		//	sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
   113  		// as part of reg-name.
   114  		// We add : because we include :port as part of host.
   115  		// We add [ ] because we include [ipv6]:port as part of host.
   116  		// We add < > because they're the only characters left that
   117  		// we could possibly allow, and Parse will reject them if we
   118  		// escape them (because hosts can't use %-encoding for
   119  		// ASCII bytes).
   120  		switch c {
   121  		case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"':
   122  			return false
   123  		}
   124  	}
   125  
   126  	switch c {
   127  	case '-', '_', '.', '~': // §2.3 Unreserved characters (mark)
   128  		return false
   129  
   130  	case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved)
   131  		// Different sections of the URL allow a few of
   132  		// the reserved characters to appear unescaped.
   133  		switch mode {
   134  		case encodePath: // §3.3
   135  			// The RFC allows : @ & = + $ but saves / ; , for assigning
   136  			// meaning to individual path segments. This package
   137  			// only manipulates the path as a whole, so we allow those
   138  			// last three as well. That leaves only ? to escape.
   139  			return c == '?'
   140  
   141  		case encodePathSegment: // §3.3
   142  			// The RFC allows : @ & = + $ but saves / ; , for assigning
   143  			// meaning to individual path segments.
   144  			return c == '/' || c == ';' || c == ',' || c == '?'
   145  
   146  		case encodeUserPassword: // §3.2.1
   147  			// The RFC allows ';', ':', '&', '=', '+', '$', and ',' in
   148  			// userinfo, so we must escape only '@', '/', and '?'.
   149  			// The parsing of userinfo treats ':' as special so we must escape
   150  			// that too.
   151  			return c == '@' || c == '/' || c == '?' || c == ':'
   152  
   153  		case encodeQueryComponent: // §3.4
   154  			// The RFC reserves (so we must escape) everything.
   155  			return true
   156  
   157  		case encodeFragment: // §4.1
   158  			// The RFC text is silent but the grammar allows
   159  			// everything, so escape nothing.
   160  			return false
   161  		}
   162  	}
   163  
   164  	if mode == encodeFragment {
   165  		// RFC 3986 §2.2 allows not escaping sub-delims. A subset of sub-delims are
   166  		// included in reserved from RFC 2396 §2.2. The remaining sub-delims do not
   167  		// need to be escaped. To minimize potential breakage, we apply two restrictions:
   168  		// (1) we always escape sub-delims outside of the fragment, and (2) we always
   169  		// escape single quote to avoid breaking callers that had previously assumed that
   170  		// single quotes would be escaped. See issue #19917.
   171  		switch c {
   172  		case '!', '(', ')', '*':
   173  			return false
   174  		}
   175  	}
   176  
   177  	// Everything else must be escaped.
   178  	return true
   179  }
   180  
   181  // QueryUnescape does the inverse transformation of [QueryEscape],
   182  // converting each 3-byte encoded substring of the form "%AB" into the
   183  // hex-decoded byte 0xAB.
   184  // It returns an error if any % is not followed by two hexadecimal
   185  // digits.
   186  func QueryUnescape(s string) (string, error) {
   187  	return unescape(s, encodeQueryComponent)
   188  }
   189  
   190  // PathUnescape does the inverse transformation of [PathEscape],
   191  // converting each 3-byte encoded substring of the form "%AB" into the
   192  // hex-decoded byte 0xAB. It returns an error if any % is not followed
   193  // by two hexadecimal digits.
   194  //
   195  // PathUnescape is identical to [QueryUnescape] except that it does not
   196  // unescape '+' to ' ' (space).
   197  func PathUnescape(s string) (string, error) {
   198  	return unescape(s, encodePathSegment)
   199  }
   200  
   201  // unescape unescapes a string; the mode specifies
   202  // which section of the URL string is being unescaped.
   203  func unescape(s string, mode encoding) (string, error) {
   204  	// Count %, check that they're well-formed.
   205  	n := 0
   206  	hasPlus := false
   207  	for i := 0; i < len(s); {
   208  		switch s[i] {
   209  		case '%':
   210  			n++
   211  			if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
   212  				s = s[i:]
   213  				if len(s) > 3 {
   214  					s = s[:3]
   215  				}
   216  				return "", EscapeError(s)
   217  			}
   218  			// Per https://tools.ietf.org/html/rfc3986#page-21
   219  			// in the host component %-encoding can only be used
   220  			// for non-ASCII bytes.
   221  			// But https://tools.ietf.org/html/rfc6874#section-2
   222  			// introduces %25 being allowed to escape a percent sign
   223  			// in IPv6 scoped-address literals. Yay.
   224  			if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" {
   225  				return "", EscapeError(s[i : i+3])
   226  			}
   227  			if mode == encodeZone {
   228  				// RFC 6874 says basically "anything goes" for zone identifiers
   229  				// and that even non-ASCII can be redundantly escaped,
   230  				// but it seems prudent to restrict %-escaped bytes here to those
   231  				// that are valid host name bytes in their unescaped form.
   232  				// That is, you can use escaping in the zone identifier but not
   233  				// to introduce bytes you couldn't just write directly.
   234  				// But Windows puts spaces here! Yay.
   235  				v := unhex(s[i+1])<<4 | unhex(s[i+2])
   236  				if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) {
   237  					return "", EscapeError(s[i : i+3])
   238  				}
   239  			}
   240  			i += 3
   241  		case '+':
   242  			hasPlus = mode == encodeQueryComponent
   243  			i++
   244  		default:
   245  			if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
   246  				return "", InvalidHostError(s[i : i+1])
   247  			}
   248  			i++
   249  		}
   250  	}
   251  
   252  	if n == 0 && !hasPlus {
   253  		return s, nil
   254  	}
   255  
   256  	var t strings.Builder
   257  	t.Grow(len(s) - 2*n)
   258  	for i := 0; i < len(s); i++ {
   259  		switch s[i] {
   260  		case '%':
   261  			t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2]))
   262  			i += 2
   263  		case '+':
   264  			if mode == encodeQueryComponent {
   265  				t.WriteByte(' ')
   266  			} else {
   267  				t.WriteByte('+')
   268  			}
   269  		default:
   270  			t.WriteByte(s[i])
   271  		}
   272  	}
   273  	return t.String(), nil
   274  }
   275  
   276  // QueryEscape escapes the string so it can be safely placed
   277  // inside a [URL] query.
   278  func QueryEscape(s string) string {
   279  	return escape(s, encodeQueryComponent)
   280  }
   281  
   282  // PathEscape escapes the string so it can be safely placed inside a [URL] path segment,
   283  // replacing special characters (including /) with %XX sequences as needed.
   284  func PathEscape(s string) string {
   285  	return escape(s, encodePathSegment)
   286  }
   287  
   288  func escape(s string, mode encoding) string {
   289  	spaceCount, hexCount := 0, 0
   290  	for i := 0; i < len(s); i++ {
   291  		c := s[i]
   292  		if shouldEscape(c, mode) {
   293  			if c == ' ' && mode == encodeQueryComponent {
   294  				spaceCount++
   295  			} else {
   296  				hexCount++
   297  			}
   298  		}
   299  	}
   300  
   301  	if spaceCount == 0 && hexCount == 0 {
   302  		return s
   303  	}
   304  
   305  	var buf [64]byte
   306  	var t []byte
   307  
   308  	required := len(s) + 2*hexCount
   309  	if required <= len(buf) {
   310  		t = buf[:required]
   311  	} else {
   312  		t = make([]byte, required)
   313  	}
   314  
   315  	if hexCount == 0 {
   316  		copy(t, s)
   317  		for i := 0; i < len(s); i++ {
   318  			if s[i] == ' ' {
   319  				t[i] = '+'
   320  			}
   321  		}
   322  		return string(t)
   323  	}
   324  
   325  	j := 0
   326  	for i := 0; i < len(s); i++ {
   327  		switch c := s[i]; {
   328  		case c == ' ' && mode == encodeQueryComponent:
   329  			t[j] = '+'
   330  			j++
   331  		case shouldEscape(c, mode):
   332  			t[j] = '%'
   333  			t[j+1] = upperhex[c>>4]
   334  			t[j+2] = upperhex[c&15]
   335  			j += 3
   336  		default:
   337  			t[j] = s[i]
   338  			j++
   339  		}
   340  	}
   341  	return string(t)
   342  }
   343  
   344  // A URL represents a parsed URL (technically, a URI reference).
   345  //
   346  // The general form represented is:
   347  //
   348  //	[scheme:][//[userinfo@]host][/]path[?query][#fragment]
   349  //
   350  // URLs that do not start with a slash after the scheme are interpreted as:
   351  //
   352  //	scheme:opaque[?query][#fragment]
   353  //
   354  // The Host field contains the host and port subcomponents of the URL.
   355  // When the port is present, it is separated from the host with a colon.
   356  // When the host is an IPv6 address, it must be enclosed in square brackets:
   357  // "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port
   358  // into a string suitable for the Host field, adding square brackets to
   359  // the host when necessary.
   360  //
   361  // Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
   362  // A consequence is that it is impossible to tell which slashes in the Path were
   363  // slashes in the raw URL and which were %2f. This distinction is rarely important,
   364  // but when it is, the code should use the [URL.EscapedPath] method, which preserves
   365  // the original encoding of Path.
   366  //
   367  // The RawPath field is an optional field which is only set when the default
   368  // encoding of Path is different from the escaped path. See the EscapedPath method
   369  // for more details.
   370  //
   371  // URL's String method uses the EscapedPath method to obtain the path.
   372  type URL struct {
   373  	Scheme      string
   374  	Opaque      string    // encoded opaque data
   375  	User        *Userinfo // username and password information
   376  	Host        string    // host or host:port (see Hostname and Port methods)
   377  	Path        string    // path (relative paths may omit leading slash)
   378  	RawPath     string    // encoded path hint (see EscapedPath method)
   379  	OmitHost    bool      // do not emit empty host (authority)
   380  	ForceQuery  bool      // append a query ('?') even if RawQuery is empty
   381  	RawQuery    string    // encoded query values, without '?'
   382  	Fragment    string    // fragment for references, without '#'
   383  	RawFragment string    // encoded fragment hint (see EscapedFragment method)
   384  }
   385  
   386  // User returns a [Userinfo] containing the provided username
   387  // and no password set.
   388  func User(username string) *Userinfo {
   389  	return &Userinfo{username, "", false}
   390  }
   391  
   392  // UserPassword returns a [Userinfo] containing the provided username
   393  // and password.
   394  //
   395  // This functionality should only be used with legacy web sites.
   396  // RFC 2396 warns that interpreting Userinfo this way
   397  // “is NOT RECOMMENDED, because the passing of authentication
   398  // information in clear text (such as URI) has proven to be a
   399  // security risk in almost every case where it has been used.”
   400  func UserPassword(username, password string) *Userinfo {
   401  	return &Userinfo{username, password, true}
   402  }
   403  
   404  // The Userinfo type is an immutable encapsulation of username and
   405  // password details for a [URL]. An existing Userinfo value is guaranteed
   406  // to have a username set (potentially empty, as allowed by RFC 2396),
   407  // and optionally a password.
   408  type Userinfo struct {
   409  	username    string
   410  	password    string
   411  	passwordSet bool
   412  }
   413  
   414  // Username returns the username.
   415  func (u *Userinfo) Username() string {
   416  	if u == nil {
   417  		return ""
   418  	}
   419  	return u.username
   420  }
   421  
   422  // Password returns the password in case it is set, and whether it is set.
   423  func (u *Userinfo) Password() (string, bool) {
   424  	if u == nil {
   425  		return "", false
   426  	}
   427  	return u.password, u.passwordSet
   428  }
   429  
   430  // String returns the encoded userinfo information in the standard form
   431  // of "username[:password]".
   432  func (u *Userinfo) String() string {
   433  	if u == nil {
   434  		return ""
   435  	}
   436  	s := escape(u.username, encodeUserPassword)
   437  	if u.passwordSet {
   438  		s += ":" + escape(u.password, encodeUserPassword)
   439  	}
   440  	return s
   441  }
   442  
   443  // Maybe rawURL is of the form scheme:path.
   444  // (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*)
   445  // If so, return scheme, path; else return "", rawURL.
   446  func getScheme(rawURL string) (scheme, path string, err error) {
   447  	for i := 0; i < len(rawURL); i++ {
   448  		c := rawURL[i]
   449  		switch {
   450  		case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
   451  		// do nothing
   452  		case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.':
   453  			if i == 0 {
   454  				return "", rawURL, nil
   455  			}
   456  		case c == ':':
   457  			if i == 0 {
   458  				return "", "", errors.New("missing protocol scheme")
   459  			}
   460  			return rawURL[:i], rawURL[i+1:], nil
   461  		default:
   462  			// we have encountered an invalid character,
   463  			// so there is no valid scheme
   464  			return "", rawURL, nil
   465  		}
   466  	}
   467  	return "", rawURL, nil
   468  }
   469  
   470  // Parse parses a raw url into a [URL] structure.
   471  //
   472  // The url may be relative (a path, without a host) or absolute
   473  // (starting with a scheme). Trying to parse a hostname and path
   474  // without a scheme is invalid but may not necessarily return an
   475  // error, due to parsing ambiguities.
   476  func Parse(rawURL string) (*URL, error) {
   477  	// Cut off #frag
   478  	u, frag, _ := strings.Cut(rawURL, "#")
   479  	url, err := parse(u, false)
   480  	if err != nil {
   481  		return nil, &Error{"parse", u, err}
   482  	}
   483  	if frag == "" {
   484  		return url, nil
   485  	}
   486  	if err = url.setFragment(frag); err != nil {
   487  		return nil, &Error{"parse", rawURL, err}
   488  	}
   489  	return url, nil
   490  }
   491  
   492  // ParseRequestURI parses a raw url into a [URL] structure. It assumes that
   493  // url was received in an HTTP request, so the url is interpreted
   494  // only as an absolute URI or an absolute path.
   495  // The string url is assumed not to have a #fragment suffix.
   496  // (Web browsers strip #fragment before sending the URL to a web server.)
   497  func ParseRequestURI(rawURL string) (*URL, error) {
   498  	url, err := parse(rawURL, true)
   499  	if err != nil {
   500  		return nil, &Error{"parse", rawURL, err}
   501  	}
   502  	return url, nil
   503  }
   504  
   505  // parse parses a URL from a string in one of two contexts. If
   506  // viaRequest is true, the URL is assumed to have arrived via an HTTP request,
   507  // in which case only absolute URLs or path-absolute relative URLs are allowed.
   508  // If viaRequest is false, all forms of relative URLs are allowed.
   509  func parse(rawURL string, viaRequest bool) (*URL, error) {
   510  	var rest string
   511  	var err error
   512  
   513  	if stringContainsCTLByte(rawURL) {
   514  		return nil, errors.New("net/url: invalid control character in URL")
   515  	}
   516  
   517  	if rawURL == "" && viaRequest {
   518  		return nil, errors.New("empty url")
   519  	}
   520  	url := new(URL)
   521  
   522  	if rawURL == "*" {
   523  		url.Path = "*"
   524  		return url, nil
   525  	}
   526  
   527  	// Split off possible leading "http:", "mailto:", etc.
   528  	// Cannot contain escaped characters.
   529  	if url.Scheme, rest, err = getScheme(rawURL); err != nil {
   530  		return nil, err
   531  	}
   532  	url.Scheme = strings.ToLower(url.Scheme)
   533  
   534  	if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 {
   535  		url.ForceQuery = true
   536  		rest = rest[:len(rest)-1]
   537  	} else {
   538  		rest, url.RawQuery, _ = strings.Cut(rest, "?")
   539  	}
   540  
   541  	if !strings.HasPrefix(rest, "/") {
   542  		if url.Scheme != "" {
   543  			// We consider rootless paths per RFC 3986 as opaque.
   544  			url.Opaque = rest
   545  			return url, nil
   546  		}
   547  		if viaRequest {
   548  			return nil, errors.New("invalid URI for request")
   549  		}
   550  
   551  		// Avoid confusion with malformed schemes, like cache_object:foo/bar.
   552  		// See golang.org/issue/16822.
   553  		//
   554  		// RFC 3986, §3.3:
   555  		// In addition, a URI reference (Section 4.1) may be a relative-path reference,
   556  		// in which case the first path segment cannot contain a colon (":") character.
   557  		if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") {
   558  			// First path segment has colon. Not allowed in relative URL.
   559  			return nil, errors.New("first path segment in URL cannot contain colon")
   560  		}
   561  	}
   562  
   563  	if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
   564  		var authority string
   565  		authority, rest = rest[2:], ""
   566  		if i := strings.Index(authority, "/"); i >= 0 {
   567  			authority, rest = authority[:i], authority[i:]
   568  		}
   569  		url.User, url.Host, err = parseAuthority(authority)
   570  		if err != nil {
   571  			return nil, err
   572  		}
   573  	} else if url.Scheme != "" && strings.HasPrefix(rest, "/") {
   574  		// OmitHost is set to true when rawURL has an empty host (authority).
   575  		// See golang.org/issue/46059.
   576  		url.OmitHost = true
   577  	}
   578  
   579  	// Set Path and, optionally, RawPath.
   580  	// RawPath is a hint of the encoding of Path. We don't want to set it if
   581  	// the default escaping of Path is equivalent, to help make sure that people
   582  	// don't rely on it in general.
   583  	if err := url.setPath(rest); err != nil {
   584  		return nil, err
   585  	}
   586  	return url, nil
   587  }
   588  
   589  func parseAuthority(authority string) (user *Userinfo, host string, err error) {
   590  	i := strings.LastIndex(authority, "@")
   591  	if i < 0 {
   592  		host, err = parseHost(authority)
   593  	} else {
   594  		host, err = parseHost(authority[i+1:])
   595  	}
   596  	if err != nil {
   597  		return nil, "", err
   598  	}
   599  	if i < 0 {
   600  		return nil, host, nil
   601  	}
   602  	userinfo := authority[:i]
   603  	if !validUserinfo(userinfo) {
   604  		return nil, "", errors.New("net/url: invalid userinfo")
   605  	}
   606  	if !strings.Contains(userinfo, ":") {
   607  		if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
   608  			return nil, "", err
   609  		}
   610  		user = User(userinfo)
   611  	} else {
   612  		username, password, _ := strings.Cut(userinfo, ":")
   613  		if username, err = unescape(username, encodeUserPassword); err != nil {
   614  			return nil, "", err
   615  		}
   616  		if password, err = unescape(password, encodeUserPassword); err != nil {
   617  			return nil, "", err
   618  		}
   619  		user = UserPassword(username, password)
   620  	}
   621  	return user, host, nil
   622  }
   623  
   624  // parseHost parses host as an authority without user
   625  // information. That is, as host[:port].
   626  func parseHost(host string) (string, error) {
   627  	if openBracketIdx := strings.LastIndex(host, "["); openBracketIdx != -1 {
   628  		// Parse an IP-Literal in RFC 3986 and RFC 6874.
   629  		// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
   630  		closeBracketIdx := strings.LastIndex(host, "]")
   631  		if closeBracketIdx < 0 {
   632  			return "", errors.New("missing ']' in host")
   633  		}
   634  
   635  		colonPort := host[closeBracketIdx+1:]
   636  		if !validOptionalPort(colonPort) {
   637  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   638  		}
   639  		unescapedColonPort, err := unescape(colonPort, encodeHost)
   640  		if err != nil {
   641  			return "", err
   642  		}
   643  
   644  		hostname := host[openBracketIdx+1 : closeBracketIdx]
   645  		var unescapedHostname string
   646  		// RFC 6874 defines that %25 (%-encoded percent) introduces
   647  		// the zone identifier, and the zone identifier can use basically
   648  		// any %-encoding it likes. That's different from the host, which
   649  		// can only %-encode non-ASCII bytes.
   650  		// We do impose some restrictions on the zone, to avoid stupidity
   651  		// like newlines.
   652  		zoneIdx := strings.Index(hostname, "%25")
   653  		if zoneIdx >= 0 {
   654  			hostPart, err := unescape(hostname[:zoneIdx], encodeHost)
   655  			if err != nil {
   656  				return "", err
   657  			}
   658  			zonePart, err := unescape(hostname[zoneIdx:], encodeZone)
   659  			if err != nil {
   660  				return "", err
   661  			}
   662  			unescapedHostname = hostPart + zonePart
   663  		} else {
   664  			var err error
   665  			unescapedHostname, err = unescape(hostname, encodeHost)
   666  			if err != nil {
   667  				return "", err
   668  			}
   669  		}
   670  
   671  		// Per RFC 3986, only a host identified by a valid
   672  		// IPv6 address can be enclosed by square brackets.
   673  		// This excludes any IPv4 or IPv4-mapped addresses.
   674  		addr, err := netip.ParseAddr(unescapedHostname)
   675  		if err != nil {
   676  			return "", fmt.Errorf("invalid host: %w", err)
   677  		}
   678  		if addr.Is4() || addr.Is4In6() {
   679  			return "", errors.New("invalid IPv6 host")
   680  		}
   681  		return "[" + unescapedHostname + "]" + unescapedColonPort, nil
   682  	} else if i := strings.LastIndex(host, ":"); i != -1 {
   683  		colonPort := host[i:]
   684  		if !validOptionalPort(colonPort) {
   685  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   686  		}
   687  	}
   688  
   689  	var err error
   690  	if host, err = unescape(host, encodeHost); err != nil {
   691  		return "", err
   692  	}
   693  	return host, nil
   694  }
   695  
   696  // setPath sets the Path and RawPath fields of the URL based on the provided
   697  // escaped path p. It maintains the invariant that RawPath is only specified
   698  // when it differs from the default encoding of the path.
   699  // For example:
   700  // - setPath("/foo/bar")   will set Path="/foo/bar" and RawPath=""
   701  // - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar"
   702  // setPath will return an error only if the provided path contains an invalid
   703  // escaping.
   704  //
   705  // setPath should be an internal detail,
   706  // but widely used packages access it using linkname.
   707  // Notable members of the hall of shame include:
   708  //   - github.com/sagernet/sing
   709  //
   710  // Do not remove or change the type signature.
   711  // See go.dev/issue/67401.
   712  //
   713  //go:linkname badSetPath net/url.(*URL).setPath
   714  func (u *URL) setPath(p string) error {
   715  	path, err := unescape(p, encodePath)
   716  	if err != nil {
   717  		return err
   718  	}
   719  	u.Path = path
   720  	if escp := escape(path, encodePath); p == escp {
   721  		// Default encoding is fine.
   722  		u.RawPath = ""
   723  	} else {
   724  		u.RawPath = p
   725  	}
   726  	return nil
   727  }
   728  
   729  // for linkname because we cannot linkname methods directly
   730  func badSetPath(*URL, string) error
   731  
   732  // EscapedPath returns the escaped form of u.Path.
   733  // In general there are multiple possible escaped forms of any path.
   734  // EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
   735  // Otherwise EscapedPath ignores u.RawPath and computes an escaped
   736  // form on its own.
   737  // The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct
   738  // their results.
   739  // In general, code should call EscapedPath instead of
   740  // reading u.RawPath directly.
   741  func (u *URL) EscapedPath() string {
   742  	if u.RawPath != "" && validEncoded(u.RawPath, encodePath) {
   743  		p, err := unescape(u.RawPath, encodePath)
   744  		if err == nil && p == u.Path {
   745  			return u.RawPath
   746  		}
   747  	}
   748  	if u.Path == "*" {
   749  		return "*" // don't escape (Issue 11202)
   750  	}
   751  	return escape(u.Path, encodePath)
   752  }
   753  
   754  // validEncoded reports whether s is a valid encoded path or fragment,
   755  // according to mode.
   756  // It must not contain any bytes that require escaping during encoding.
   757  func validEncoded(s string, mode encoding) bool {
   758  	for i := 0; i < len(s); i++ {
   759  		// RFC 3986, Appendix A.
   760  		// pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
   761  		// shouldEscape is not quite compliant with the RFC,
   762  		// so we check the sub-delims ourselves and let
   763  		// shouldEscape handle the others.
   764  		switch s[i] {
   765  		case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
   766  			// ok
   767  		case '[', ']':
   768  			// ok - not specified in RFC 3986 but left alone by modern browsers
   769  		case '%':
   770  			// ok - percent encoded, will decode
   771  		default:
   772  			if shouldEscape(s[i], mode) {
   773  				return false
   774  			}
   775  		}
   776  	}
   777  	return true
   778  }
   779  
   780  // setFragment is like setPath but for Fragment/RawFragment.
   781  func (u *URL) setFragment(f string) error {
   782  	frag, err := unescape(f, encodeFragment)
   783  	if err != nil {
   784  		return err
   785  	}
   786  	u.Fragment = frag
   787  	if escf := escape(frag, encodeFragment); f == escf {
   788  		// Default encoding is fine.
   789  		u.RawFragment = ""
   790  	} else {
   791  		u.RawFragment = f
   792  	}
   793  	return nil
   794  }
   795  
   796  // EscapedFragment returns the escaped form of u.Fragment.
   797  // In general there are multiple possible escaped forms of any fragment.
   798  // EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment.
   799  // Otherwise EscapedFragment ignores u.RawFragment and computes an escaped
   800  // form on its own.
   801  // The [URL.String] method uses EscapedFragment to construct its result.
   802  // In general, code should call EscapedFragment instead of
   803  // reading u.RawFragment directly.
   804  func (u *URL) EscapedFragment() string {
   805  	if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) {
   806  		f, err := unescape(u.RawFragment, encodeFragment)
   807  		if err == nil && f == u.Fragment {
   808  			return u.RawFragment
   809  		}
   810  	}
   811  	return escape(u.Fragment, encodeFragment)
   812  }
   813  
   814  // validOptionalPort reports whether port is either an empty string
   815  // or matches /^:\d*$/
   816  func validOptionalPort(port string) bool {
   817  	if port == "" {
   818  		return true
   819  	}
   820  	if port[0] != ':' {
   821  		return false
   822  	}
   823  	for _, b := range port[1:] {
   824  		if b < '0' || b > '9' {
   825  			return false
   826  		}
   827  	}
   828  	return true
   829  }
   830  
   831  // String reassembles the [URL] into a valid URL string.
   832  // The general form of the result is one of:
   833  //
   834  //	scheme:opaque?query#fragment
   835  //	scheme://userinfo@host/path?query#fragment
   836  //
   837  // If u.Opaque is non-empty, String uses the first form;
   838  // otherwise it uses the second form.
   839  // Any non-ASCII characters in host are escaped.
   840  // To obtain the path, String uses u.EscapedPath().
   841  //
   842  // In the second form, the following rules apply:
   843  //   - if u.Scheme is empty, scheme: is omitted.
   844  //   - if u.User is nil, userinfo@ is omitted.
   845  //   - if u.Host is empty, host/ is omitted.
   846  //   - if u.Scheme and u.Host are empty and u.User is nil,
   847  //     the entire scheme://userinfo@host/ is omitted.
   848  //   - if u.Host is non-empty and u.Path begins with a /,
   849  //     the form host/path does not add its own /.
   850  //   - if u.RawQuery is empty, ?query is omitted.
   851  //   - if u.Fragment is empty, #fragment is omitted.
   852  func (u *URL) String() string {
   853  	var buf strings.Builder
   854  
   855  	n := len(u.Scheme)
   856  	if u.Opaque != "" {
   857  		n += len(u.Opaque)
   858  	} else {
   859  		if !u.OmitHost && (u.Scheme != "" || u.Host != "" || u.User != nil) {
   860  			username := u.User.Username()
   861  			password, _ := u.User.Password()
   862  			n += len(username) + len(password) + len(u.Host)
   863  		}
   864  		n += len(u.Path)
   865  	}
   866  	n += len(u.RawQuery) + len(u.RawFragment)
   867  	n += len(":" + "//" + "//" + ":" + "@" + "/" + "./" + "?" + "#")
   868  	buf.Grow(n)
   869  
   870  	if u.Scheme != "" {
   871  		buf.WriteString(u.Scheme)
   872  		buf.WriteByte(':')
   873  	}
   874  	if u.Opaque != "" {
   875  		buf.WriteString(u.Opaque)
   876  	} else {
   877  		if u.Scheme != "" || u.Host != "" || u.User != nil {
   878  			if u.OmitHost && u.Host == "" && u.User == nil {
   879  				// omit empty host
   880  			} else {
   881  				if u.Host != "" || u.Path != "" || u.User != nil {
   882  					buf.WriteString("//")
   883  				}
   884  				if ui := u.User; ui != nil {
   885  					buf.WriteString(ui.String())
   886  					buf.WriteByte('@')
   887  				}
   888  				if h := u.Host; h != "" {
   889  					buf.WriteString(escape(h, encodeHost))
   890  				}
   891  			}
   892  		}
   893  		path := u.EscapedPath()
   894  		if path != "" && path[0] != '/' && u.Host != "" {
   895  			buf.WriteByte('/')
   896  		}
   897  		if buf.Len() == 0 {
   898  			// RFC 3986 §4.2
   899  			// A path segment that contains a colon character (e.g., "this:that")
   900  			// cannot be used as the first segment of a relative-path reference, as
   901  			// it would be mistaken for a scheme name. Such a segment must be
   902  			// preceded by a dot-segment (e.g., "./this:that") to make a relative-
   903  			// path reference.
   904  			if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") {
   905  				buf.WriteString("./")
   906  			}
   907  		}
   908  		buf.WriteString(path)
   909  	}
   910  	if u.ForceQuery || u.RawQuery != "" {
   911  		buf.WriteByte('?')
   912  		buf.WriteString(u.RawQuery)
   913  	}
   914  	if u.Fragment != "" {
   915  		buf.WriteByte('#')
   916  		buf.WriteString(u.EscapedFragment())
   917  	}
   918  	return buf.String()
   919  }
   920  
   921  // Redacted is like [URL.String] but replaces any password with "xxxxx".
   922  // Only the password in u.User is redacted.
   923  func (u *URL) Redacted() string {
   924  	if u == nil {
   925  		return ""
   926  	}
   927  
   928  	ru := *u
   929  	if _, has := ru.User.Password(); has {
   930  		ru.User = UserPassword(ru.User.Username(), "xxxxx")
   931  	}
   932  	return ru.String()
   933  }
   934  
   935  // Values maps a string key to a list of values.
   936  // It is typically used for query parameters and form values.
   937  // Unlike in the http.Header map, the keys in a Values map
   938  // are case-sensitive.
   939  type Values map[string][]string
   940  
   941  // Get gets the first value associated with the given key.
   942  // If there are no values associated with the key, Get returns
   943  // the empty string. To access multiple values, use the map
   944  // directly.
   945  func (v Values) Get(key string) string {
   946  	vs := v[key]
   947  	if len(vs) == 0 {
   948  		return ""
   949  	}
   950  	return vs[0]
   951  }
   952  
   953  // Set sets the key to value. It replaces any existing
   954  // values.
   955  func (v Values) Set(key, value string) {
   956  	v[key] = []string{value}
   957  }
   958  
   959  // Add adds the value to key. It appends to any existing
   960  // values associated with key.
   961  func (v Values) Add(key, value string) {
   962  	v[key] = append(v[key], value)
   963  }
   964  
   965  // Del deletes the values associated with key.
   966  func (v Values) Del(key string) {
   967  	delete(v, key)
   968  }
   969  
   970  // Has checks whether a given key is set.
   971  func (v Values) Has(key string) bool {
   972  	_, ok := v[key]
   973  	return ok
   974  }
   975  
   976  // ParseQuery parses the URL-encoded query string and returns
   977  // a map listing the values specified for each key.
   978  // ParseQuery always returns a non-nil map containing all the
   979  // valid query parameters found; err describes the first decoding error
   980  // encountered, if any.
   981  //
   982  // Query is expected to be a list of key=value settings separated by ampersands.
   983  // A setting without an equals sign is interpreted as a key set to an empty
   984  // value.
   985  // Settings containing a non-URL-encoded semicolon are considered invalid.
   986  func ParseQuery(query string) (Values, error) {
   987  	m := make(Values)
   988  	err := parseQuery(m, query)
   989  	return m, err
   990  }
   991  
   992  func parseQuery(m Values, query string) (err error) {
   993  	for query != "" {
   994  		var key string
   995  		key, query, _ = strings.Cut(query, "&")
   996  		if strings.Contains(key, ";") {
   997  			err = fmt.Errorf("invalid semicolon separator in query")
   998  			continue
   999  		}
  1000  		if key == "" {
  1001  			continue
  1002  		}
  1003  		key, value, _ := strings.Cut(key, "=")
  1004  		key, err1 := QueryUnescape(key)
  1005  		if err1 != nil {
  1006  			if err == nil {
  1007  				err = err1
  1008  			}
  1009  			continue
  1010  		}
  1011  		value, err1 = QueryUnescape(value)
  1012  		if err1 != nil {
  1013  			if err == nil {
  1014  				err = err1
  1015  			}
  1016  			continue
  1017  		}
  1018  		m[key] = append(m[key], value)
  1019  	}
  1020  	return err
  1021  }
  1022  
  1023  // Encode encodes the values into “URL encoded” form
  1024  // ("bar=baz&foo=quux") sorted by key.
  1025  func (v Values) Encode() string {
  1026  	if len(v) == 0 {
  1027  		return ""
  1028  	}
  1029  	var buf strings.Builder
  1030  	for _, k := range slices.Sorted(maps.Keys(v)) {
  1031  		vs := v[k]
  1032  		keyEscaped := QueryEscape(k)
  1033  		for _, v := range vs {
  1034  			if buf.Len() > 0 {
  1035  				buf.WriteByte('&')
  1036  			}
  1037  			buf.WriteString(keyEscaped)
  1038  			buf.WriteByte('=')
  1039  			buf.WriteString(QueryEscape(v))
  1040  		}
  1041  	}
  1042  	return buf.String()
  1043  }
  1044  
  1045  // resolvePath applies special path segments from refs and applies
  1046  // them to base, per RFC 3986.
  1047  func resolvePath(base, ref string) string {
  1048  	var full string
  1049  	if ref == "" {
  1050  		full = base
  1051  	} else if ref[0] != '/' {
  1052  		i := strings.LastIndex(base, "/")
  1053  		full = base[:i+1] + ref
  1054  	} else {
  1055  		full = ref
  1056  	}
  1057  	if full == "" {
  1058  		return ""
  1059  	}
  1060  
  1061  	var (
  1062  		elem string
  1063  		dst  strings.Builder
  1064  	)
  1065  	first := true
  1066  	remaining := full
  1067  	// We want to return a leading '/', so write it now.
  1068  	dst.WriteByte('/')
  1069  	found := true
  1070  	for found {
  1071  		elem, remaining, found = strings.Cut(remaining, "/")
  1072  		if elem == "." {
  1073  			first = false
  1074  			// drop
  1075  			continue
  1076  		}
  1077  
  1078  		if elem == ".." {
  1079  			// Ignore the leading '/' we already wrote.
  1080  			str := dst.String()[1:]
  1081  			index := strings.LastIndexByte(str, '/')
  1082  
  1083  			dst.Reset()
  1084  			dst.WriteByte('/')
  1085  			if index == -1 {
  1086  				first = true
  1087  			} else {
  1088  				dst.WriteString(str[:index])
  1089  			}
  1090  		} else {
  1091  			if !first {
  1092  				dst.WriteByte('/')
  1093  			}
  1094  			dst.WriteString(elem)
  1095  			first = false
  1096  		}
  1097  	}
  1098  
  1099  	if elem == "." || elem == ".." {
  1100  		dst.WriteByte('/')
  1101  	}
  1102  
  1103  	// We wrote an initial '/', but we don't want two.
  1104  	r := dst.String()
  1105  	if len(r) > 1 && r[1] == '/' {
  1106  		r = r[1:]
  1107  	}
  1108  	return r
  1109  }
  1110  
  1111  // IsAbs reports whether the [URL] is absolute.
  1112  // Absolute means that it has a non-empty scheme.
  1113  func (u *URL) IsAbs() bool {
  1114  	return u.Scheme != ""
  1115  }
  1116  
  1117  // Parse parses a [URL] in the context of the receiver. The provided URL
  1118  // may be relative or absolute. Parse returns nil, err on parse
  1119  // failure, otherwise its return value is the same as [URL.ResolveReference].
  1120  func (u *URL) Parse(ref string) (*URL, error) {
  1121  	refURL, err := Parse(ref)
  1122  	if err != nil {
  1123  		return nil, err
  1124  	}
  1125  	return u.ResolveReference(refURL), nil
  1126  }
  1127  
  1128  // ResolveReference resolves a URI reference to an absolute URI from
  1129  // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference
  1130  // may be relative or absolute. ResolveReference always returns a new
  1131  // [URL] instance, even if the returned URL is identical to either the
  1132  // base or reference. If ref is an absolute URL, then ResolveReference
  1133  // ignores base and returns a copy of ref.
  1134  func (u *URL) ResolveReference(ref *URL) *URL {
  1135  	url := *ref
  1136  	if ref.Scheme == "" {
  1137  		url.Scheme = u.Scheme
  1138  	}
  1139  	if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
  1140  		// The "absoluteURI" or "net_path" cases.
  1141  		// We can ignore the error from setPath since we know we provided a
  1142  		// validly-escaped path.
  1143  		url.setPath(resolvePath(ref.EscapedPath(), ""))
  1144  		return &url
  1145  	}
  1146  	if ref.Opaque != "" {
  1147  		url.User = nil
  1148  		url.Host = ""
  1149  		url.Path = ""
  1150  		return &url
  1151  	}
  1152  	if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" {
  1153  		url.RawQuery = u.RawQuery
  1154  		if ref.Fragment == "" {
  1155  			url.Fragment = u.Fragment
  1156  			url.RawFragment = u.RawFragment
  1157  		}
  1158  	}
  1159  	if ref.Path == "" && u.Opaque != "" {
  1160  		url.Opaque = u.Opaque
  1161  		url.User = nil
  1162  		url.Host = ""
  1163  		url.Path = ""
  1164  		return &url
  1165  	}
  1166  	// The "abs_path" or "rel_path" cases.
  1167  	url.Host = u.Host
  1168  	url.User = u.User
  1169  	url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
  1170  	return &url
  1171  }
  1172  
  1173  // Query parses RawQuery and returns the corresponding values.
  1174  // It silently discards malformed value pairs.
  1175  // To check errors use [ParseQuery].
  1176  func (u *URL) Query() Values {
  1177  	v, _ := ParseQuery(u.RawQuery)
  1178  	return v
  1179  }
  1180  
  1181  // RequestURI returns the encoded path?query or opaque?query
  1182  // string that would be used in an HTTP request for u.
  1183  func (u *URL) RequestURI() string {
  1184  	result := u.Opaque
  1185  	if result == "" {
  1186  		result = u.EscapedPath()
  1187  		if result == "" {
  1188  			result = "/"
  1189  		}
  1190  	} else {
  1191  		if strings.HasPrefix(result, "//") {
  1192  			result = u.Scheme + ":" + result
  1193  		}
  1194  	}
  1195  	if u.ForceQuery || u.RawQuery != "" {
  1196  		result += "?" + u.RawQuery
  1197  	}
  1198  	return result
  1199  }
  1200  
  1201  // Hostname returns u.Host, stripping any valid port number if present.
  1202  //
  1203  // If the result is enclosed in square brackets, as literal IPv6 addresses are,
  1204  // the square brackets are removed from the result.
  1205  func (u *URL) Hostname() string {
  1206  	host, _ := splitHostPort(u.Host)
  1207  	return host
  1208  }
  1209  
  1210  // Port returns the port part of u.Host, without the leading colon.
  1211  //
  1212  // If u.Host doesn't contain a valid numeric port, Port returns an empty string.
  1213  func (u *URL) Port() string {
  1214  	_, port := splitHostPort(u.Host)
  1215  	return port
  1216  }
  1217  
  1218  // splitHostPort separates host and port. If the port is not valid, it returns
  1219  // the entire input as host, and it doesn't check the validity of the host.
  1220  // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
  1221  func splitHostPort(hostPort string) (host, port string) {
  1222  	host = hostPort
  1223  
  1224  	colon := strings.LastIndexByte(host, ':')
  1225  	if colon != -1 && validOptionalPort(host[colon:]) {
  1226  		host, port = host[:colon], host[colon+1:]
  1227  	}
  1228  
  1229  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  1230  		host = host[1 : len(host)-1]
  1231  	}
  1232  
  1233  	return
  1234  }
  1235  
  1236  // Marshaling interface implementations.
  1237  // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs.
  1238  
  1239  func (u *URL) MarshalBinary() (text []byte, err error) {
  1240  	return u.AppendBinary(nil)
  1241  }
  1242  
  1243  func (u *URL) AppendBinary(b []byte) ([]byte, error) {
  1244  	return append(b, u.String()...), nil
  1245  }
  1246  
  1247  func (u *URL) UnmarshalBinary(text []byte) error {
  1248  	u1, err := Parse(string(text))
  1249  	if err != nil {
  1250  		return err
  1251  	}
  1252  	*u = *u1
  1253  	return nil
  1254  }
  1255  
  1256  // JoinPath returns a new [URL] with the provided path elements joined to
  1257  // any existing path and the resulting path cleaned of any ./ or ../ elements.
  1258  // Any sequences of multiple / characters will be reduced to a single /.
  1259  func (u *URL) JoinPath(elem ...string) *URL {
  1260  	elem = append([]string{u.EscapedPath()}, elem...)
  1261  	var p string
  1262  	if !strings.HasPrefix(elem[0], "/") {
  1263  		// Return a relative path if u is relative,
  1264  		// but ensure that it contains no ../ elements.
  1265  		elem[0] = "/" + elem[0]
  1266  		p = path.Join(elem...)[1:]
  1267  	} else {
  1268  		p = path.Join(elem...)
  1269  	}
  1270  	// path.Join will remove any trailing slashes.
  1271  	// Preserve at least one.
  1272  	if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
  1273  		p += "/"
  1274  	}
  1275  	url := *u
  1276  	url.setPath(p)
  1277  	return &url
  1278  }
  1279  
  1280  // validUserinfo reports whether s is a valid userinfo string per RFC 3986
  1281  // Section 3.2.1:
  1282  //
  1283  //	userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
  1284  //	unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1285  //	sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
  1286  //	              / "*" / "+" / "," / ";" / "="
  1287  //
  1288  // It doesn't validate pct-encoded. The caller does that via func unescape.
  1289  func validUserinfo(s string) bool {
  1290  	for _, r := range s {
  1291  		if 'A' <= r && r <= 'Z' {
  1292  			continue
  1293  		}
  1294  		if 'a' <= r && r <= 'z' {
  1295  			continue
  1296  		}
  1297  		if '0' <= r && r <= '9' {
  1298  			continue
  1299  		}
  1300  		switch r {
  1301  		case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
  1302  			'(', ')', '*', '+', ',', ';', '=', '%', '@':
  1303  			continue
  1304  		default:
  1305  			return false
  1306  		}
  1307  	}
  1308  	return true
  1309  }
  1310  
  1311  // stringContainsCTLByte reports whether s contains any ASCII control character.
  1312  func stringContainsCTLByte(s string) bool {
  1313  	for i := 0; i < len(s); i++ {
  1314  		b := s[i]
  1315  		if b < ' ' || b == 0x7f {
  1316  			return true
  1317  		}
  1318  	}
  1319  	return false
  1320  }
  1321  
  1322  // JoinPath returns a [URL] string with the provided path elements joined to
  1323  // the existing path of base and the resulting path cleaned of any ./ or ../ elements.
  1324  func JoinPath(base string, elem ...string) (result string, err error) {
  1325  	url, err := Parse(base)
  1326  	if err != nil {
  1327  		return
  1328  	}
  1329  	result = url.JoinPath(elem...).String()
  1330  	return
  1331  }
  1332  

View as plain text