github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/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 vs := v[key] 887 if len(vs) == 0 { 888 return "" 889 } 890 return vs[0] 891 } 892 893 // Set sets the key to value. It replaces any existing 894 // values. 895 func (v Values) Set(key, value string) { 896 v[key] = []string{value} 897 } 898 899 // Add adds the value to key. It appends to any existing 900 // values associated with key. 901 func (v Values) Add(key, value string) { 902 v[key] = append(v[key], value) 903 } 904 905 // Del deletes the values associated with key. 906 func (v Values) Del(key string) { 907 delete(v, key) 908 } 909 910 // Has checks whether a given key is set. 911 func (v Values) Has(key string) bool { 912 _, ok := v[key] 913 return ok 914 } 915 916 // ParseQuery parses the URL-encoded query string and returns 917 // a map listing the values specified for each key. 918 // ParseQuery always returns a non-nil map containing all the 919 // valid query parameters found; err describes the first decoding error 920 // encountered, if any. 921 // 922 // Query is expected to be a list of key=value settings separated by ampersands. 923 // A setting without an equals sign is interpreted as a key set to an empty 924 // value. 925 // Settings containing a non-URL-encoded semicolon are considered invalid. 926 func ParseQuery(query string) (Values, error) { 927 m := make(Values) 928 err := parseQuery(m, query) 929 return m, err 930 } 931 932 func parseQuery(m Values, query string) (err error) { 933 for query != "" { 934 var key string 935 key, query, _ = strings.Cut(query, "&") 936 if strings.Contains(key, ";") { 937 err = fmt.Errorf("invalid semicolon separator in query") 938 continue 939 } 940 if key == "" { 941 continue 942 } 943 key, value, _ := strings.Cut(key, "=") 944 key, err1 := QueryUnescape(key) 945 if err1 != nil { 946 if err == nil { 947 err = err1 948 } 949 continue 950 } 951 value, err1 = QueryUnescape(value) 952 if err1 != nil { 953 if err == nil { 954 err = err1 955 } 956 continue 957 } 958 m[key] = append(m[key], value) 959 } 960 return err 961 } 962 963 // Encode encodes the values into “URL encoded” form 964 // ("bar=baz&foo=quux") sorted by key. 965 func (v Values) Encode() string { 966 if v == nil { 967 return "" 968 } 969 var buf strings.Builder 970 keys := make([]string, 0, len(v)) 971 for k := range v { 972 keys = append(keys, k) 973 } 974 sort.Strings(keys) 975 for _, k := range keys { 976 vs := v[k] 977 keyEscaped := QueryEscape(k) 978 for _, v := range vs { 979 if buf.Len() > 0 { 980 buf.WriteByte('&') 981 } 982 buf.WriteString(keyEscaped) 983 buf.WriteByte('=') 984 buf.WriteString(QueryEscape(v)) 985 } 986 } 987 return buf.String() 988 } 989 990 // resolvePath applies special path segments from refs and applies 991 // them to base, per RFC 3986. 992 func resolvePath(base, ref string) string { 993 var full string 994 if ref == "" { 995 full = base 996 } else if ref[0] != '/' { 997 i := strings.LastIndex(base, "/") 998 full = base[:i+1] + ref 999 } else { 1000 full = ref 1001 } 1002 if full == "" { 1003 return "" 1004 } 1005 1006 var ( 1007 elem string 1008 dst strings.Builder 1009 ) 1010 first := true 1011 remaining := full 1012 // We want to return a leading '/', so write it now. 1013 dst.WriteByte('/') 1014 found := true 1015 for found { 1016 elem, remaining, found = strings.Cut(remaining, "/") 1017 if elem == "." { 1018 first = false 1019 // drop 1020 continue 1021 } 1022 1023 if elem == ".." { 1024 // Ignore the leading '/' we already wrote. 1025 str := dst.String()[1:] 1026 index := strings.LastIndexByte(str, '/') 1027 1028 dst.Reset() 1029 dst.WriteByte('/') 1030 if index == -1 { 1031 first = true 1032 } else { 1033 dst.WriteString(str[:index]) 1034 } 1035 } else { 1036 if !first { 1037 dst.WriteByte('/') 1038 } 1039 dst.WriteString(elem) 1040 first = false 1041 } 1042 } 1043 1044 if elem == "." || elem == ".." { 1045 dst.WriteByte('/') 1046 } 1047 1048 // We wrote an initial '/', but we don't want two. 1049 r := dst.String() 1050 if len(r) > 1 && r[1] == '/' { 1051 r = r[1:] 1052 } 1053 return r 1054 } 1055 1056 // IsAbs reports whether the URL is absolute. 1057 // Absolute means that it has a non-empty scheme. 1058 func (u *URL) IsAbs() bool { 1059 return u.Scheme != "" 1060 } 1061 1062 // Parse parses a URL in the context of the receiver. The provided URL 1063 // may be relative or absolute. Parse returns nil, err on parse 1064 // failure, otherwise its return value is the same as ResolveReference. 1065 func (u *URL) Parse(ref string) (*URL, error) { 1066 refURL, err := Parse(ref) 1067 if err != nil { 1068 return nil, err 1069 } 1070 return u.ResolveReference(refURL), nil 1071 } 1072 1073 // ResolveReference resolves a URI reference to an absolute URI from 1074 // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference 1075 // may be relative or absolute. ResolveReference always returns a new 1076 // URL instance, even if the returned URL is identical to either the 1077 // base or reference. If ref is an absolute URL, then ResolveReference 1078 // ignores base and returns a copy of ref. 1079 func (u *URL) ResolveReference(ref *URL) *URL { 1080 url := *ref 1081 if ref.Scheme == "" { 1082 url.Scheme = u.Scheme 1083 } 1084 if ref.Scheme != "" || ref.Host != "" || ref.User != nil { 1085 // The "absoluteURI" or "net_path" cases. 1086 // We can ignore the error from setPath since we know we provided a 1087 // validly-escaped path. 1088 url.setPath(resolvePath(ref.EscapedPath(), "")) 1089 return &url 1090 } 1091 if ref.Opaque != "" { 1092 url.User = nil 1093 url.Host = "" 1094 url.Path = "" 1095 return &url 1096 } 1097 if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" { 1098 url.RawQuery = u.RawQuery 1099 if ref.Fragment == "" { 1100 url.Fragment = u.Fragment 1101 url.RawFragment = u.RawFragment 1102 } 1103 } 1104 // The "abs_path" or "rel_path" cases. 1105 url.Host = u.Host 1106 url.User = u.User 1107 url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath())) 1108 return &url 1109 } 1110 1111 // Query parses RawQuery and returns the corresponding values. 1112 // It silently discards malformed value pairs. 1113 // To check errors use ParseQuery. 1114 func (u *URL) Query() Values { 1115 v, _ := ParseQuery(u.RawQuery) 1116 return v 1117 } 1118 1119 // RequestURI returns the encoded path?query or opaque?query 1120 // string that would be used in an HTTP request for u. 1121 func (u *URL) RequestURI() string { 1122 result := u.Opaque 1123 if result == "" { 1124 result = u.EscapedPath() 1125 if result == "" { 1126 result = "/" 1127 } 1128 } else { 1129 if strings.HasPrefix(result, "//") { 1130 result = u.Scheme + ":" + result 1131 } 1132 } 1133 if u.ForceQuery || u.RawQuery != "" { 1134 result += "?" + u.RawQuery 1135 } 1136 return result 1137 } 1138 1139 // Hostname returns u.Host, stripping any valid port number if present. 1140 // 1141 // If the result is enclosed in square brackets, as literal IPv6 addresses are, 1142 // the square brackets are removed from the result. 1143 func (u *URL) Hostname() string { 1144 host, _ := splitHostPort(u.Host) 1145 return host 1146 } 1147 1148 // Port returns the port part of u.Host, without the leading colon. 1149 // 1150 // If u.Host doesn't contain a valid numeric port, Port returns an empty string. 1151 func (u *URL) Port() string { 1152 _, port := splitHostPort(u.Host) 1153 return port 1154 } 1155 1156 // splitHostPort separates host and port. If the port is not valid, it returns 1157 // the entire input as host, and it doesn't check the validity of the host. 1158 // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric. 1159 func splitHostPort(hostPort string) (host, port string) { 1160 host = hostPort 1161 1162 colon := strings.LastIndexByte(host, ':') 1163 if colon != -1 && validOptionalPort(host[colon:]) { 1164 host, port = host[:colon], host[colon+1:] 1165 } 1166 1167 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { 1168 host = host[1 : len(host)-1] 1169 } 1170 1171 return 1172 } 1173 1174 // Marshaling interface implementations. 1175 // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs. 1176 1177 func (u *URL) MarshalBinary() (text []byte, err error) { 1178 return []byte(u.String()), nil 1179 } 1180 1181 func (u *URL) UnmarshalBinary(text []byte) error { 1182 u1, err := Parse(string(text)) 1183 if err != nil { 1184 return err 1185 } 1186 *u = *u1 1187 return nil 1188 } 1189 1190 // JoinPath returns a new URL with the provided path elements joined to 1191 // any existing path and the resulting path cleaned of any ./ or ../ elements. 1192 // Any sequences of multiple / characters will be reduced to a single /. 1193 func (u *URL) JoinPath(elem ...string) *URL { 1194 elem = append([]string{u.EscapedPath()}, elem...) 1195 var p string 1196 if !strings.HasPrefix(elem[0], "/") { 1197 // Return a relative path if u is relative, 1198 // but ensure that it contains no ../ elements. 1199 elem[0] = "/" + elem[0] 1200 p = path.Join(elem...)[1:] 1201 } else { 1202 p = path.Join(elem...) 1203 } 1204 // path.Join will remove any trailing slashes. 1205 // Preserve at least one. 1206 if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") { 1207 p += "/" 1208 } 1209 url := *u 1210 url.setPath(p) 1211 return &url 1212 } 1213 1214 // validUserinfo reports whether s is a valid userinfo string per RFC 3986 1215 // Section 3.2.1: 1216 // 1217 // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) 1218 // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" 1219 // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" 1220 // / "*" / "+" / "," / ";" / "=" 1221 // 1222 // It doesn't validate pct-encoded. The caller does that via func unescape. 1223 func validUserinfo(s string) bool { 1224 for _, r := range s { 1225 if 'A' <= r && r <= 'Z' { 1226 continue 1227 } 1228 if 'a' <= r && r <= 'z' { 1229 continue 1230 } 1231 if '0' <= r && r <= '9' { 1232 continue 1233 } 1234 switch r { 1235 case '-', '.', '_', ':', '~', '!', '$', '&', '\'', 1236 '(', ')', '*', '+', ',', ';', '=', '%', '@': 1237 continue 1238 default: 1239 return false 1240 } 1241 } 1242 return true 1243 } 1244 1245 // stringContainsCTLByte reports whether s contains any ASCII control character. 1246 func stringContainsCTLByte(s string) bool { 1247 for i := 0; i < len(s); i++ { 1248 b := s[i] 1249 if b < ' ' || b == 0x7f { 1250 return true 1251 } 1252 } 1253 return false 1254 } 1255 1256 // JoinPath returns a URL string with the provided path elements joined to 1257 // the existing path of base and the resulting path cleaned of any ./ or ../ elements. 1258 func JoinPath(base string, elem ...string) (result string, err error) { 1259 url, err := Parse(base) 1260 if err != nil { 1261 return 1262 } 1263 result = url.JoinPath(elem...).String() 1264 return 1265 }