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