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