github.com/remobjects/goldbaselibrary@v0.0.0-20230924164425-d458680a936b/Source/Gold/net/url/url_test.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 6 7 import ( 8 "bytes" 9 encodingPkg "encoding" 10 "encoding/gob" 11 "encoding/json" 12 "fmt" 13 "io" 14 "net" 15 "reflect" 16 "strings" 17 "testing" 18 ) 19 20 type URLTest struct { 21 in string 22 out *URL // expected parse; RawPath="" means same as Path 23 roundtrip string // expected result of reserializing the URL; empty means same as "in". 24 } 25 26 var urltests = []URLTest{ 27 // no path 28 { 29 "http://www.google.com", 30 &URL{ 31 Scheme: "http", 32 Host: "www.google.com", 33 }, 34 "", 35 }, 36 // path 37 { 38 "http://www.google.com/", 39 &URL{ 40 Scheme: "http", 41 Host: "www.google.com", 42 Path: "/", 43 }, 44 "", 45 }, 46 // path with hex escaping 47 { 48 "http://www.google.com/file%20one%26two", 49 &URL{ 50 Scheme: "http", 51 Host: "www.google.com", 52 Path: "/file one&two", 53 RawPath: "/file%20one%26two", 54 }, 55 "", 56 }, 57 // user 58 { 59 "ftp://webmaster@www.google.com/", 60 &URL{ 61 Scheme: "ftp", 62 User: User("webmaster"), 63 Host: "www.google.com", 64 Path: "/", 65 }, 66 "", 67 }, 68 // escape sequence in username 69 { 70 "ftp://john%20doe@www.google.com/", 71 &URL{ 72 Scheme: "ftp", 73 User: User("john doe"), 74 Host: "www.google.com", 75 Path: "/", 76 }, 77 "ftp://john%20doe@www.google.com/", 78 }, 79 // empty query 80 { 81 "http://www.google.com/?", 82 &URL{ 83 Scheme: "http", 84 Host: "www.google.com", 85 Path: "/", 86 ForceQuery: true, 87 }, 88 "", 89 }, 90 // query ending in question mark (Issue 14573) 91 { 92 "http://www.google.com/?foo=bar?", 93 &URL{ 94 Scheme: "http", 95 Host: "www.google.com", 96 Path: "/", 97 RawQuery: "foo=bar?", 98 }, 99 "", 100 }, 101 // query 102 { 103 "http://www.google.com/?q=go+language", 104 &URL{ 105 Scheme: "http", 106 Host: "www.google.com", 107 Path: "/", 108 RawQuery: "q=go+language", 109 }, 110 "", 111 }, 112 // query with hex escaping: NOT parsed 113 { 114 "http://www.google.com/?q=go%20language", 115 &URL{ 116 Scheme: "http", 117 Host: "www.google.com", 118 Path: "/", 119 RawQuery: "q=go%20language", 120 }, 121 "", 122 }, 123 // %20 outside query 124 { 125 "http://www.google.com/a%20b?q=c+d", 126 &URL{ 127 Scheme: "http", 128 Host: "www.google.com", 129 Path: "/a b", 130 RawQuery: "q=c+d", 131 }, 132 "", 133 }, 134 // path without leading /, so no parsing 135 { 136 "http:www.google.com/?q=go+language", 137 &URL{ 138 Scheme: "http", 139 Opaque: "www.google.com/", 140 RawQuery: "q=go+language", 141 }, 142 "http:www.google.com/?q=go+language", 143 }, 144 // path without leading /, so no parsing 145 { 146 "http:%2f%2fwww.google.com/?q=go+language", 147 &URL{ 148 Scheme: "http", 149 Opaque: "%2f%2fwww.google.com/", 150 RawQuery: "q=go+language", 151 }, 152 "http:%2f%2fwww.google.com/?q=go+language", 153 }, 154 // non-authority with path 155 { 156 "mailto:/webmaster@golang.org", 157 &URL{ 158 Scheme: "mailto", 159 Path: "/webmaster@golang.org", 160 }, 161 "mailto:///webmaster@golang.org", // unfortunate compromise 162 }, 163 // non-authority 164 { 165 "mailto:webmaster@golang.org", 166 &URL{ 167 Scheme: "mailto", 168 Opaque: "webmaster@golang.org", 169 }, 170 "", 171 }, 172 // unescaped :// in query should not create a scheme 173 { 174 "/foo?query=http://bad", 175 &URL{ 176 Path: "/foo", 177 RawQuery: "query=http://bad", 178 }, 179 "", 180 }, 181 // leading // without scheme should create an authority 182 { 183 "//foo", 184 &URL{ 185 Host: "foo", 186 }, 187 "", 188 }, 189 // leading // without scheme, with userinfo, path, and query 190 { 191 "//user@foo/path?a=b", 192 &URL{ 193 User: User("user"), 194 Host: "foo", 195 Path: "/path", 196 RawQuery: "a=b", 197 }, 198 "", 199 }, 200 // Three leading slashes isn't an authority, but doesn't return an error. 201 // (We can't return an error, as this code is also used via 202 // ServeHTTP -> ReadRequest -> Parse, which is arguably a 203 // different URL parsing context, but currently shares the 204 // same codepath) 205 { 206 "///threeslashes", 207 &URL{ 208 Path: "///threeslashes", 209 }, 210 "", 211 }, 212 { 213 "http://user:password@google.com", 214 &URL{ 215 Scheme: "http", 216 User: UserPassword("user", "password"), 217 Host: "google.com", 218 }, 219 "http://user:password@google.com", 220 }, 221 // unescaped @ in username should not confuse host 222 { 223 "http://j@ne:password@google.com", 224 &URL{ 225 Scheme: "http", 226 User: UserPassword("j@ne", "password"), 227 Host: "google.com", 228 }, 229 "http://j%40ne:password@google.com", 230 }, 231 // unescaped @ in password should not confuse host 232 { 233 "http://jane:p@ssword@google.com", 234 &URL{ 235 Scheme: "http", 236 User: UserPassword("jane", "p@ssword"), 237 Host: "google.com", 238 }, 239 "http://jane:p%40ssword@google.com", 240 }, 241 { 242 "http://j@ne:password@google.com/p@th?q=@go", 243 &URL{ 244 Scheme: "http", 245 User: UserPassword("j@ne", "password"), 246 Host: "google.com", 247 Path: "/p@th", 248 RawQuery: "q=@go", 249 }, 250 "http://j%40ne:password@google.com/p@th?q=@go", 251 }, 252 { 253 "http://www.google.com/?q=go+language#foo", 254 &URL{ 255 Scheme: "http", 256 Host: "www.google.com", 257 Path: "/", 258 RawQuery: "q=go+language", 259 Fragment: "foo", 260 }, 261 "", 262 }, 263 { 264 "http://www.google.com/?q=go+language#foo%26bar", 265 &URL{ 266 Scheme: "http", 267 Host: "www.google.com", 268 Path: "/", 269 RawQuery: "q=go+language", 270 Fragment: "foo&bar", 271 }, 272 "http://www.google.com/?q=go+language#foo&bar", 273 }, 274 { 275 "file:///home/adg/rabbits", 276 &URL{ 277 Scheme: "file", 278 Host: "", 279 Path: "/home/adg/rabbits", 280 }, 281 "file:///home/adg/rabbits", 282 }, 283 // "Windows" paths are no exception to the rule. 284 // See golang.org/issue/6027, especially comment #9. 285 { 286 "file:///C:/FooBar/Baz.txt", 287 &URL{ 288 Scheme: "file", 289 Host: "", 290 Path: "/C:/FooBar/Baz.txt", 291 }, 292 "file:///C:/FooBar/Baz.txt", 293 }, 294 // case-insensitive scheme 295 { 296 "MaIlTo:webmaster@golang.org", 297 &URL{ 298 Scheme: "mailto", 299 Opaque: "webmaster@golang.org", 300 }, 301 "mailto:webmaster@golang.org", 302 }, 303 // Relative path 304 { 305 "a/b/c", 306 &URL{ 307 Path: "a/b/c", 308 }, 309 "a/b/c", 310 }, 311 // escaped '?' in username and password 312 { 313 "http://%3Fam:pa%3Fsword@google.com", 314 &URL{ 315 Scheme: "http", 316 User: UserPassword("?am", "pa?sword"), 317 Host: "google.com", 318 }, 319 "", 320 }, 321 // host subcomponent; IPv4 address in RFC 3986 322 { 323 "http://192.168.0.1/", 324 &URL{ 325 Scheme: "http", 326 Host: "192.168.0.1", 327 Path: "/", 328 }, 329 "", 330 }, 331 // host and port subcomponents; IPv4 address in RFC 3986 332 { 333 "http://192.168.0.1:8080/", 334 &URL{ 335 Scheme: "http", 336 Host: "192.168.0.1:8080", 337 Path: "/", 338 }, 339 "", 340 }, 341 // host subcomponent; IPv6 address in RFC 3986 342 { 343 "http://[fe80::1]/", 344 &URL{ 345 Scheme: "http", 346 Host: "[fe80::1]", 347 Path: "/", 348 }, 349 "", 350 }, 351 // host and port subcomponents; IPv6 address in RFC 3986 352 { 353 "http://[fe80::1]:8080/", 354 &URL{ 355 Scheme: "http", 356 Host: "[fe80::1]:8080", 357 Path: "/", 358 }, 359 "", 360 }, 361 // host subcomponent; IPv6 address with zone identifier in RFC 6874 362 { 363 "http://[fe80::1%25en0]/", // alphanum zone identifier 364 &URL{ 365 Scheme: "http", 366 Host: "[fe80::1%en0]", 367 Path: "/", 368 }, 369 "", 370 }, 371 // host and port subcomponents; IPv6 address with zone identifier in RFC 6874 372 { 373 "http://[fe80::1%25en0]:8080/", // alphanum zone identifier 374 &URL{ 375 Scheme: "http", 376 Host: "[fe80::1%en0]:8080", 377 Path: "/", 378 }, 379 "", 380 }, 381 // host subcomponent; IPv6 address with zone identifier in RFC 6874 382 { 383 "http://[fe80::1%25%65%6e%301-._~]/", // percent-encoded+unreserved zone identifier 384 &URL{ 385 Scheme: "http", 386 Host: "[fe80::1%en01-._~]", 387 Path: "/", 388 }, 389 "http://[fe80::1%25en01-._~]/", 390 }, 391 // host and port subcomponents; IPv6 address with zone identifier in RFC 6874 392 { 393 "http://[fe80::1%25%65%6e%301-._~]:8080/", // percent-encoded+unreserved zone identifier 394 &URL{ 395 Scheme: "http", 396 Host: "[fe80::1%en01-._~]:8080", 397 Path: "/", 398 }, 399 "http://[fe80::1%25en01-._~]:8080/", 400 }, 401 // alternate escapings of path survive round trip 402 { 403 "http://rest.rsc.io/foo%2fbar/baz%2Fquux?alt=media", 404 &URL{ 405 Scheme: "http", 406 Host: "rest.rsc.io", 407 Path: "/foo/bar/baz/quux", 408 RawPath: "/foo%2fbar/baz%2Fquux", 409 RawQuery: "alt=media", 410 }, 411 "", 412 }, 413 // issue 12036 414 { 415 "mysql://a,b,c/bar", 416 &URL{ 417 Scheme: "mysql", 418 Host: "a,b,c", 419 Path: "/bar", 420 }, 421 "", 422 }, 423 // worst case host, still round trips 424 { 425 "scheme://!$&'()*+,;=hello!:1/path", 426 &URL{ 427 Scheme: "scheme", 428 Host: "!$&'()*+,;=hello!:1", 429 Path: "/path", 430 }, 431 "", 432 }, 433 // worst case path, still round trips 434 { 435 "http://host/!$&'()*+,;=:@[hello]", 436 &URL{ 437 Scheme: "http", 438 Host: "host", 439 Path: "/!$&'()*+,;=:@[hello]", 440 RawPath: "/!$&'()*+,;=:@[hello]", 441 }, 442 "", 443 }, 444 // golang.org/issue/5684 445 { 446 "http://example.com/oid/[order_id]", 447 &URL{ 448 Scheme: "http", 449 Host: "example.com", 450 Path: "/oid/[order_id]", 451 RawPath: "/oid/[order_id]", 452 }, 453 "", 454 }, 455 // golang.org/issue/12200 (colon with empty port) 456 { 457 "http://192.168.0.2:8080/foo", 458 &URL{ 459 Scheme: "http", 460 Host: "192.168.0.2:8080", 461 Path: "/foo", 462 }, 463 "", 464 }, 465 { 466 "http://192.168.0.2:/foo", 467 &URL{ 468 Scheme: "http", 469 Host: "192.168.0.2:", 470 Path: "/foo", 471 }, 472 "", 473 }, 474 { 475 // Malformed IPv6 but still accepted. 476 "http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080/foo", 477 &URL{ 478 Scheme: "http", 479 Host: "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080", 480 Path: "/foo", 481 }, 482 "", 483 }, 484 { 485 // Malformed IPv6 but still accepted. 486 "http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:/foo", 487 &URL{ 488 Scheme: "http", 489 Host: "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:", 490 Path: "/foo", 491 }, 492 "", 493 }, 494 { 495 "http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080/foo", 496 &URL{ 497 Scheme: "http", 498 Host: "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080", 499 Path: "/foo", 500 }, 501 "", 502 }, 503 { 504 "http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:/foo", 505 &URL{ 506 Scheme: "http", 507 Host: "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:", 508 Path: "/foo", 509 }, 510 "", 511 }, 512 // golang.org/issue/7991 and golang.org/issue/12719 (non-ascii %-encoded in host) 513 { 514 "http://hello.世界.com/foo", 515 &URL{ 516 Scheme: "http", 517 Host: "hello.世界.com", 518 Path: "/foo", 519 }, 520 "http://hello.%E4%B8%96%E7%95%8C.com/foo", 521 }, 522 { 523 "http://hello.%e4%b8%96%e7%95%8c.com/foo", 524 &URL{ 525 Scheme: "http", 526 Host: "hello.世界.com", 527 Path: "/foo", 528 }, 529 "http://hello.%E4%B8%96%E7%95%8C.com/foo", 530 }, 531 { 532 "http://hello.%E4%B8%96%E7%95%8C.com/foo", 533 &URL{ 534 Scheme: "http", 535 Host: "hello.世界.com", 536 Path: "/foo", 537 }, 538 "", 539 }, 540 // golang.org/issue/10433 (path beginning with //) 541 { 542 "http://example.com//foo", 543 &URL{ 544 Scheme: "http", 545 Host: "example.com", 546 Path: "//foo", 547 }, 548 "", 549 }, 550 // test that we can reparse the host names we accept. 551 { 552 "myscheme://authority<\"hi\">/foo", 553 &URL{ 554 Scheme: "myscheme", 555 Host: "authority<\"hi\">", 556 Path: "/foo", 557 }, 558 "", 559 }, 560 // spaces in hosts are disallowed but escaped spaces in IPv6 scope IDs are grudgingly OK. 561 // This happens on Windows. 562 // golang.org/issue/14002 563 { 564 "tcp://[2020::2020:20:2020:2020%25Windows%20Loves%20Spaces]:2020", 565 &URL{ 566 Scheme: "tcp", 567 Host: "[2020::2020:20:2020:2020%Windows Loves Spaces]:2020", 568 }, 569 "", 570 }, 571 // test we can roundtrip magnet url 572 // fix issue https://golang.org/issue/20054 573 { 574 "magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn", 575 &URL{ 576 Scheme: "magnet", 577 Host: "", 578 Path: "", 579 RawQuery: "xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn", 580 }, 581 "magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn", 582 }, 583 { 584 "mailto:?subject=hi", 585 &URL{ 586 Scheme: "mailto", 587 Host: "", 588 Path: "", 589 RawQuery: "subject=hi", 590 }, 591 "mailto:?subject=hi", 592 }, 593 } 594 595 // more useful string for debugging than fmt's struct printer 596 func ufmt(u *URL) string { 597 var user, pass interface{} 598 if u.User != nil { 599 user = u.User.Username() 600 if p, ok := u.User.Password(); ok { 601 pass = p 602 } 603 } 604 return fmt.Sprintf("opaque=%q, scheme=%q, user=%#v, pass=%#v, host=%q, path=%q, rawpath=%q, rawq=%q, frag=%q, forcequery=%v", 605 u.Opaque, u.Scheme, user, pass, u.Host, u.Path, u.RawPath, u.RawQuery, u.Fragment, u.ForceQuery) 606 } 607 608 func BenchmarkString(b *testing.B) { 609 b.StopTimer() 610 b.ReportAllocs() 611 for _, tt := range urltests { 612 u, err := Parse(tt.in) 613 if err != nil { 614 b.Errorf("Parse(%q) returned error %s", tt.in, err) 615 continue 616 } 617 if tt.roundtrip == "" { 618 continue 619 } 620 b.StartTimer() 621 var g string 622 for i := 0; i < b.N; i++ { 623 g = u.String() 624 } 625 b.StopTimer() 626 if w := tt.roundtrip; b.N > 0 && g != w { 627 b.Errorf("Parse(%q).String() == %q, want %q", tt.in, g, w) 628 } 629 } 630 } 631 632 func TestParse(t *testing.T) { 633 for _, tt := range urltests { 634 u, err := Parse(tt.in) 635 if err != nil { 636 t.Errorf("Parse(%q) returned error %v", tt.in, err) 637 continue 638 } 639 if !reflect.DeepEqual(u, tt.out) { 640 t.Errorf("Parse(%q):\n\tgot %v\n\twant %v\n", tt.in, ufmt(u), ufmt(tt.out)) 641 } 642 } 643 } 644 645 const pathThatLooksSchemeRelative = "//not.a.user@not.a.host/just/a/path" 646 647 var parseRequestURLTests = []struct { 648 url string 649 expectedValid bool 650 }{ 651 {"http://foo.com", true}, 652 {"http://foo.com/", true}, 653 {"http://foo.com/path", true}, 654 {"/", true}, 655 {pathThatLooksSchemeRelative, true}, 656 {"//not.a.user@%66%6f%6f.com/just/a/path/also", true}, 657 {"*", true}, 658 {"http://192.168.0.1/", true}, 659 {"http://192.168.0.1:8080/", true}, 660 {"http://[fe80::1]/", true}, 661 {"http://[fe80::1]:8080/", true}, 662 663 // Tests exercising RFC 6874 compliance: 664 {"http://[fe80::1%25en0]/", true}, // with alphanum zone identifier 665 {"http://[fe80::1%25en0]:8080/", true}, // with alphanum zone identifier 666 {"http://[fe80::1%25%65%6e%301-._~]/", true}, // with percent-encoded+unreserved zone identifier 667 {"http://[fe80::1%25%65%6e%301-._~]:8080/", true}, // with percent-encoded+unreserved zone identifier 668 669 {"foo.html", false}, 670 {"../dir/", false}, 671 {"http://192.168.0.%31/", false}, 672 {"http://192.168.0.%31:8080/", false}, 673 {"http://[fe80::%31]/", false}, 674 {"http://[fe80::%31]:8080/", false}, 675 {"http://[fe80::%31%25en0]/", false}, 676 {"http://[fe80::%31%25en0]:8080/", false}, 677 678 // These two cases are valid as textual representations as 679 // described in RFC 4007, but are not valid as address 680 // literals with IPv6 zone identifiers in URIs as described in 681 // RFC 6874. 682 {"http://[fe80::1%en0]/", false}, 683 {"http://[fe80::1%en0]:8080/", false}, 684 } 685 686 func TestParseRequestURI(t *testing.T) { 687 for _, test := range parseRequestURLTests { 688 _, err := ParseRequestURI(test.url) 689 if test.expectedValid && err != nil { 690 t.Errorf("ParseRequestURI(%q) gave err %v; want no error", test.url, err) 691 } else if !test.expectedValid && err == nil { 692 t.Errorf("ParseRequestURI(%q) gave nil error; want some error", test.url) 693 } 694 } 695 696 url, err := ParseRequestURI(pathThatLooksSchemeRelative) 697 if err != nil { 698 t.Fatalf("Unexpected error %v", err) 699 } 700 if url.Path != pathThatLooksSchemeRelative { 701 t.Errorf("ParseRequestURI path:\ngot %q\nwant %q", url.Path, pathThatLooksSchemeRelative) 702 } 703 } 704 705 var stringURLTests = []struct { 706 url URL 707 want string 708 }{ 709 // No leading slash on path should prepend slash on String() call 710 { 711 url: URL{ 712 Scheme: "http", 713 Host: "www.google.com", 714 Path: "search", 715 }, 716 want: "http://www.google.com/search", 717 }, 718 // Relative path with first element containing ":" should be prepended with "./", golang.org/issue/17184 719 { 720 url: URL{ 721 Path: "this:that", 722 }, 723 want: "./this:that", 724 }, 725 // Relative path with second element containing ":" should not be prepended with "./" 726 { 727 url: URL{ 728 Path: "here/this:that", 729 }, 730 want: "here/this:that", 731 }, 732 // Non-relative path with first element containing ":" should not be prepended with "./" 733 { 734 url: URL{ 735 Scheme: "http", 736 Host: "www.google.com", 737 Path: "this:that", 738 }, 739 want: "http://www.google.com/this:that", 740 }, 741 } 742 743 func TestURLString(t *testing.T) { 744 for _, tt := range urltests { 745 u, err := Parse(tt.in) 746 if err != nil { 747 t.Errorf("Parse(%q) returned error %s", tt.in, err) 748 continue 749 } 750 expected := tt.in 751 if tt.roundtrip != "" { 752 expected = tt.roundtrip 753 } 754 s := u.String() 755 if s != expected { 756 t.Errorf("Parse(%q).String() == %q (expected %q)", tt.in, s, expected) 757 } 758 } 759 760 for _, tt := range stringURLTests { 761 if got := tt.url.String(); got != tt.want { 762 t.Errorf("%+v.String() = %q; want %q", tt.url, got, tt.want) 763 } 764 } 765 } 766 767 type EscapeTest struct { 768 in string 769 out string 770 err error 771 } 772 773 var unescapeTests = []EscapeTest{ 774 { 775 "", 776 "", 777 nil, 778 }, 779 { 780 "abc", 781 "abc", 782 nil, 783 }, 784 { 785 "1%41", 786 "1A", 787 nil, 788 }, 789 { 790 "1%41%42%43", 791 "1ABC", 792 nil, 793 }, 794 { 795 "%4a", 796 "J", 797 nil, 798 }, 799 { 800 "%6F", 801 "o", 802 nil, 803 }, 804 { 805 "%", // not enough characters after % 806 "", 807 EscapeError("%"), 808 }, 809 { 810 "%a", // not enough characters after % 811 "", 812 EscapeError("%a"), 813 }, 814 { 815 "%1", // not enough characters after % 816 "", 817 EscapeError("%1"), 818 }, 819 { 820 "123%45%6", // not enough characters after % 821 "", 822 EscapeError("%6"), 823 }, 824 { 825 "%zzzzz", // invalid hex digits 826 "", 827 EscapeError("%zz"), 828 }, 829 { 830 "a+b", 831 "a b", 832 nil, 833 }, 834 { 835 "a%20b", 836 "a b", 837 nil, 838 }, 839 } 840 841 func TestUnescape(t *testing.T) { 842 for _, tt := range unescapeTests { 843 actual, err := QueryUnescape(tt.in) 844 if actual != tt.out || (err != nil) != (tt.err != nil) { 845 t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err) 846 } 847 848 in := tt.in 849 out := tt.out 850 if strings.Contains(tt.in, "+") { 851 in = strings.ReplaceAll(tt.in, "+", "%20") 852 actual, err := PathUnescape(in) 853 if actual != tt.out || (err != nil) != (tt.err != nil) { 854 t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, tt.out, tt.err) 855 } 856 if tt.err == nil { 857 s, err := QueryUnescape(strings.ReplaceAll(tt.in, "+", "XXX")) 858 if err != nil { 859 continue 860 } 861 in = tt.in 862 out = strings.ReplaceAll(s, "XXX", "+") 863 } 864 } 865 866 actual, err = PathUnescape(in) 867 if actual != out || (err != nil) != (tt.err != nil) { 868 t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, out, tt.err) 869 } 870 } 871 } 872 873 var queryEscapeTests = []EscapeTest{ 874 { 875 "", 876 "", 877 nil, 878 }, 879 { 880 "abc", 881 "abc", 882 nil, 883 }, 884 { 885 "one two", 886 "one+two", 887 nil, 888 }, 889 { 890 "10%", 891 "10%25", 892 nil, 893 }, 894 { 895 " ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;", 896 "+%3F%26%3D%23%2B%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09%3A%2F%40%24%27%28%29%2A%2C%3B", 897 nil, 898 }, 899 } 900 901 func TestQueryEscape(t *testing.T) { 902 for _, tt := range queryEscapeTests { 903 actual := QueryEscape(tt.in) 904 if tt.out != actual { 905 t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out) 906 } 907 908 // for bonus points, verify that escape:unescape is an identity. 909 roundtrip, err := QueryUnescape(actual) 910 if roundtrip != tt.in || err != nil { 911 t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]") 912 } 913 } 914 } 915 916 var pathEscapeTests = []EscapeTest{ 917 { 918 "", 919 "", 920 nil, 921 }, 922 { 923 "abc", 924 "abc", 925 nil, 926 }, 927 { 928 "abc+def", 929 "abc+def", 930 nil, 931 }, 932 { 933 "a/b", 934 "a%2Fb", 935 nil, 936 }, 937 { 938 "one two", 939 "one%20two", 940 nil, 941 }, 942 { 943 "10%", 944 "10%25", 945 nil, 946 }, 947 { 948 " ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;", 949 "%20%3F&=%23+%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09:%2F@$%27%28%29%2A%2C%3B", 950 nil, 951 }, 952 } 953 954 func TestPathEscape(t *testing.T) { 955 for _, tt := range pathEscapeTests { 956 actual := PathEscape(tt.in) 957 if tt.out != actual { 958 t.Errorf("PathEscape(%q) = %q, want %q", tt.in, actual, tt.out) 959 } 960 961 // for bonus points, verify that escape:unescape is an identity. 962 roundtrip, err := PathUnescape(actual) 963 if roundtrip != tt.in || err != nil { 964 t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]") 965 } 966 } 967 } 968 969 //var userinfoTests = []UserinfoTest{ 970 // {"user", "password", "user:password"}, 971 // {"foo:bar", "~!@#$%^&*()_+{}|[]\\-=`:;'\"<>?,./", 972 // "foo%3Abar:~!%40%23$%25%5E&*()_+%7B%7D%7C%5B%5D%5C-=%60%3A;'%22%3C%3E?,.%2F"}, 973 //} 974 975 type EncodeQueryTest struct { 976 m Values 977 expected string 978 } 979 980 var encodeQueryTests = []EncodeQueryTest{ 981 {nil, ""}, 982 {Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"}, 983 {Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"}, 984 {Values{ 985 "a": {"a1", "a2", "a3"}, 986 "b": {"b1", "b2", "b3"}, 987 "c": {"c1", "c2", "c3"}, 988 }, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"}, 989 } 990 991 func TestEncodeQuery(t *testing.T) { 992 for _, tt := range encodeQueryTests { 993 if q := tt.m.Encode(); q != tt.expected { 994 t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected) 995 } 996 } 997 } 998 999 var resolvePathTests = []struct { 1000 base, ref, expected string 1001 }{ 1002 {"a/b", ".", "/a/"}, 1003 {"a/b", "c", "/a/c"}, 1004 {"a/b", "..", "/"}, 1005 {"a/", "..", "/"}, 1006 {"a/", "../..", "/"}, 1007 {"a/b/c", "..", "/a/"}, 1008 {"a/b/c", "../d", "/a/d"}, 1009 {"a/b/c", ".././d", "/a/d"}, 1010 {"a/b", "./..", "/"}, 1011 {"a/./b", ".", "/a/"}, 1012 {"a/../", ".", "/"}, 1013 {"a/.././b", "c", "/c"}, 1014 } 1015 1016 func TestResolvePath(t *testing.T) { 1017 for _, test := range resolvePathTests { 1018 got := resolvePath(test.base, test.ref) 1019 if got != test.expected { 1020 t.Errorf("For %q + %q got %q; expected %q", test.base, test.ref, got, test.expected) 1021 } 1022 } 1023 } 1024 1025 var resolveReferenceTests = []struct { 1026 base, rel, expected string 1027 }{ 1028 // Absolute URL references 1029 {"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"}, 1030 {"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"}, 1031 {"http://foo.com/", "https://bar.com/?", "https://bar.com/?"}, 1032 {"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"}, 1033 1034 // Path-absolute references 1035 {"http://foo.com/bar", "/baz", "http://foo.com/baz"}, 1036 {"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"}, 1037 {"http://foo.com/bar?a=b", "/baz?", "http://foo.com/baz?"}, 1038 {"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"}, 1039 1040 // Multiple slashes 1041 {"http://foo.com/bar", "http://foo.com//baz", "http://foo.com//baz"}, 1042 {"http://foo.com/bar", "http://foo.com///baz/quux", "http://foo.com///baz/quux"}, 1043 1044 // Scheme-relative 1045 {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"}, 1046 1047 // Path-relative references: 1048 1049 // ... current directory 1050 {"http://foo.com", ".", "http://foo.com/"}, 1051 {"http://foo.com/bar", ".", "http://foo.com/"}, 1052 {"http://foo.com/bar/", ".", "http://foo.com/bar/"}, 1053 1054 // ... going down 1055 {"http://foo.com", "bar", "http://foo.com/bar"}, 1056 {"http://foo.com/", "bar", "http://foo.com/bar"}, 1057 {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"}, 1058 1059 // ... going up 1060 {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"}, 1061 {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"}, 1062 {"http://foo.com/bar", "..", "http://foo.com/"}, 1063 {"http://foo.com/bar/baz", "./..", "http://foo.com/"}, 1064 // ".." in the middle (issue 3560) 1065 {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"}, 1066 {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"}, 1067 {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"}, 1068 {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"}, 1069 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"}, 1070 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"}, 1071 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"}, 1072 {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"}, 1073 1074 // Remove any dot-segments prior to forming the target URI. 1075 // http://tools.ietf.org/html/rfc3986#section-5.2.4 1076 {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"}, 1077 1078 // Triple dot isn't special 1079 {"http://foo.com/bar", "...", "http://foo.com/..."}, 1080 1081 // Fragment 1082 {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"}, 1083 {"http://example.org/", "#!$&%27()*+,;=", "http://example.org/#!$&%27()*+,;="}, 1084 1085 // Paths with escaping (issue 16947). 1086 {"http://foo.com/foo%2fbar/", "../baz", "http://foo.com/baz"}, 1087 {"http://foo.com/1/2%2f/3%2f4/5", "../../a/b/c", "http://foo.com/1/a/b/c"}, 1088 {"http://foo.com/1/2/3", "./a%2f../../b/..%2fc", "http://foo.com/1/2/b/..%2fc"}, 1089 {"http://foo.com/1/2%2f/3%2f4/5", "./a%2f../b/../c", "http://foo.com/1/2%2f/3%2f4/a%2f../c"}, 1090 {"http://foo.com/foo%20bar/", "../baz", "http://foo.com/baz"}, 1091 {"http://foo.com/foo", "../bar%2fbaz", "http://foo.com/bar%2fbaz"}, 1092 {"http://foo.com/foo%2dbar/", "./baz-quux", "http://foo.com/foo%2dbar/baz-quux"}, 1093 1094 // RFC 3986: Normal Examples 1095 // http://tools.ietf.org/html/rfc3986#section-5.4.1 1096 {"http://a/b/c/d;p?q", "g:h", "g:h"}, 1097 {"http://a/b/c/d;p?q", "g", "http://a/b/c/g"}, 1098 {"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"}, 1099 {"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"}, 1100 {"http://a/b/c/d;p?q", "/g", "http://a/g"}, 1101 {"http://a/b/c/d;p?q", "//g", "http://g"}, 1102 {"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"}, 1103 {"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"}, 1104 {"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"}, 1105 {"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"}, 1106 {"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"}, 1107 {"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"}, 1108 {"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"}, 1109 {"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"}, 1110 {"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"}, 1111 {"http://a/b/c/d;p?q", ".", "http://a/b/c/"}, 1112 {"http://a/b/c/d;p?q", "./", "http://a/b/c/"}, 1113 {"http://a/b/c/d;p?q", "..", "http://a/b/"}, 1114 {"http://a/b/c/d;p?q", "../", "http://a/b/"}, 1115 {"http://a/b/c/d;p?q", "../g", "http://a/b/g"}, 1116 {"http://a/b/c/d;p?q", "../..", "http://a/"}, 1117 {"http://a/b/c/d;p?q", "../../", "http://a/"}, 1118 {"http://a/b/c/d;p?q", "../../g", "http://a/g"}, 1119 1120 // RFC 3986: Abnormal Examples 1121 // http://tools.ietf.org/html/rfc3986#section-5.4.2 1122 {"http://a/b/c/d;p?q", "../../../g", "http://a/g"}, 1123 {"http://a/b/c/d;p?q", "../../../../g", "http://a/g"}, 1124 {"http://a/b/c/d;p?q", "/./g", "http://a/g"}, 1125 {"http://a/b/c/d;p?q", "/../g", "http://a/g"}, 1126 {"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."}, 1127 {"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"}, 1128 {"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."}, 1129 {"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"}, 1130 {"http://a/b/c/d;p?q", "./../g", "http://a/b/g"}, 1131 {"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"}, 1132 {"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"}, 1133 {"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"}, 1134 {"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"}, 1135 {"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"}, 1136 {"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"}, 1137 {"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"}, 1138 {"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"}, 1139 {"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"}, 1140 1141 // Extras. 1142 {"https://a/b/c/d;p?q", "//g?q", "https://g?q"}, 1143 {"https://a/b/c/d;p?q", "//g#s", "https://g#s"}, 1144 {"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"}, 1145 {"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"}, 1146 {"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"}, 1147 } 1148 1149 func TestResolveReference(t *testing.T) { 1150 mustParse := func(url string) *URL { 1151 u, err := Parse(url) 1152 if err != nil { 1153 t.Fatalf("Parse(%q) got err %v", url, err) 1154 } 1155 return u 1156 } 1157 opaque := &URL{Scheme: "scheme", Opaque: "opaque"} 1158 for _, test := range resolveReferenceTests { 1159 base := mustParse(test.base) 1160 rel := mustParse(test.rel) 1161 url := base.ResolveReference(rel) 1162 if got := url.String(); got != test.expected { 1163 t.Errorf("URL(%q).ResolveReference(%q)\ngot %q\nwant %q", test.base, test.rel, got, test.expected) 1164 } 1165 // Ensure that new instances are returned. 1166 if base == url { 1167 t.Errorf("Expected URL.ResolveReference to return new URL instance.") 1168 } 1169 // Test the convenience wrapper too. 1170 url, err := base.Parse(test.rel) 1171 if err != nil { 1172 t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err) 1173 } else if got := url.String(); got != test.expected { 1174 t.Errorf("URL(%q).Parse(%q)\ngot %q\nwant %q", test.base, test.rel, got, test.expected) 1175 } else if base == url { 1176 // Ensure that new instances are returned for the wrapper too. 1177 t.Errorf("Expected URL.Parse to return new URL instance.") 1178 } 1179 // Ensure Opaque resets the URL. 1180 url = base.ResolveReference(opaque) 1181 if *url != *opaque { 1182 t.Errorf("ResolveReference failed to resolve opaque URL:\ngot %#v\nwant %#v", url, opaque) 1183 } 1184 // Test the convenience wrapper with an opaque URL too. 1185 url, err = base.Parse("scheme:opaque") 1186 if err != nil { 1187 t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err) 1188 } else if *url != *opaque { 1189 t.Errorf("Parse failed to resolve opaque URL:\ngot %#v\nwant %#v", opaque, url) 1190 } else if base == url { 1191 // Ensure that new instances are returned, again. 1192 t.Errorf("Expected URL.Parse to return new URL instance.") 1193 } 1194 } 1195 } 1196 1197 func TestQueryValues(t *testing.T) { 1198 u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2") 1199 v := u.Query() 1200 if len(v) != 2 { 1201 t.Errorf("got %d keys in Query values, want 2", len(v)) 1202 } 1203 if g, e := v.Get("foo"), "bar"; g != e { 1204 t.Errorf("Get(foo) = %q, want %q", g, e) 1205 } 1206 // Case sensitive: 1207 if g, e := v.Get("Foo"), ""; g != e { 1208 t.Errorf("Get(Foo) = %q, want %q", g, e) 1209 } 1210 if g, e := v.Get("bar"), "1"; g != e { 1211 t.Errorf("Get(bar) = %q, want %q", g, e) 1212 } 1213 if g, e := v.Get("baz"), ""; g != e { 1214 t.Errorf("Get(baz) = %q, want %q", g, e) 1215 } 1216 v.Del("bar") 1217 if g, e := v.Get("bar"), ""; g != e { 1218 t.Errorf("second Get(bar) = %q, want %q", g, e) 1219 } 1220 } 1221 1222 type parseTest struct { 1223 query string 1224 out Values 1225 } 1226 1227 var parseTests = []parseTest{ 1228 { 1229 query: "a=1&b=2", 1230 out: Values{"a": []string{"1"}, "b": []string{"2"}}, 1231 }, 1232 { 1233 query: "a=1&a=2&a=banana", 1234 out: Values{"a": []string{"1", "2", "banana"}}, 1235 }, 1236 { 1237 query: "ascii=%3Ckey%3A+0x90%3E", 1238 out: Values{"ascii": []string{"<key: 0x90>"}}, 1239 }, 1240 { 1241 query: "a=1;b=2", 1242 out: Values{"a": []string{"1"}, "b": []string{"2"}}, 1243 }, 1244 { 1245 query: "a=1&a=2;a=banana", 1246 out: Values{"a": []string{"1", "2", "banana"}}, 1247 }, 1248 } 1249 1250 func TestParseQuery(t *testing.T) { 1251 for i, test := range parseTests { 1252 form, err := ParseQuery(test.query) 1253 if err != nil { 1254 t.Errorf("test %d: Unexpected error: %v", i, err) 1255 continue 1256 } 1257 if len(form) != len(test.out) { 1258 t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out)) 1259 } 1260 for k, evs := range test.out { 1261 vs, ok := form[k] 1262 if !ok { 1263 t.Errorf("test %d: Missing key %q", i, k) 1264 continue 1265 } 1266 if len(vs) != len(evs) { 1267 t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs)) 1268 continue 1269 } 1270 for j, ev := range evs { 1271 if v := vs[j]; v != ev { 1272 t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev) 1273 } 1274 } 1275 } 1276 } 1277 } 1278 1279 type RequestURITest struct { 1280 url *URL 1281 out string 1282 } 1283 1284 var requritests = []RequestURITest{ 1285 { 1286 &URL{ 1287 Scheme: "http", 1288 Host: "example.com", 1289 Path: "", 1290 }, 1291 "/", 1292 }, 1293 { 1294 &URL{ 1295 Scheme: "http", 1296 Host: "example.com", 1297 Path: "/a b", 1298 }, 1299 "/a%20b", 1300 }, 1301 // golang.org/issue/4860 variant 1 1302 { 1303 &URL{ 1304 Scheme: "http", 1305 Host: "example.com", 1306 Opaque: "/%2F/%2F/", 1307 }, 1308 "/%2F/%2F/", 1309 }, 1310 // golang.org/issue/4860 variant 2 1311 { 1312 &URL{ 1313 Scheme: "http", 1314 Host: "example.com", 1315 Opaque: "//other.example.com/%2F/%2F/", 1316 }, 1317 "http://other.example.com/%2F/%2F/", 1318 }, 1319 // better fix for issue 4860 1320 { 1321 &URL{ 1322 Scheme: "http", 1323 Host: "example.com", 1324 Path: "/////", 1325 RawPath: "/%2F/%2F/", 1326 }, 1327 "/%2F/%2F/", 1328 }, 1329 { 1330 &URL{ 1331 Scheme: "http", 1332 Host: "example.com", 1333 Path: "/////", 1334 RawPath: "/WRONG/", // ignored because doesn't match Path 1335 }, 1336 "/////", 1337 }, 1338 { 1339 &URL{ 1340 Scheme: "http", 1341 Host: "example.com", 1342 Path: "/a b", 1343 RawQuery: "q=go+language", 1344 }, 1345 "/a%20b?q=go+language", 1346 }, 1347 { 1348 &URL{ 1349 Scheme: "http", 1350 Host: "example.com", 1351 Path: "/a b", 1352 RawPath: "/a b", // ignored because invalid 1353 RawQuery: "q=go+language", 1354 }, 1355 "/a%20b?q=go+language", 1356 }, 1357 { 1358 &URL{ 1359 Scheme: "http", 1360 Host: "example.com", 1361 Path: "/a?b", 1362 RawPath: "/a?b", // ignored because invalid 1363 RawQuery: "q=go+language", 1364 }, 1365 "/a%3Fb?q=go+language", 1366 }, 1367 { 1368 &URL{ 1369 Scheme: "myschema", 1370 Opaque: "opaque", 1371 }, 1372 "opaque", 1373 }, 1374 { 1375 &URL{ 1376 Scheme: "myschema", 1377 Opaque: "opaque", 1378 RawQuery: "q=go+language", 1379 }, 1380 "opaque?q=go+language", 1381 }, 1382 { 1383 &URL{ 1384 Scheme: "http", 1385 Host: "example.com", 1386 Path: "//foo", 1387 }, 1388 "//foo", 1389 }, 1390 { 1391 &URL{ 1392 Scheme: "http", 1393 Host: "example.com", 1394 Path: "/foo", 1395 ForceQuery: true, 1396 }, 1397 "/foo?", 1398 }, 1399 } 1400 1401 func TestRequestURI(t *testing.T) { 1402 for _, tt := range requritests { 1403 s := tt.url.RequestURI() 1404 if s != tt.out { 1405 t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out) 1406 } 1407 } 1408 } 1409 1410 func TestParseFailure(t *testing.T) { 1411 // Test that the first parse error is returned. 1412 const url = "%gh&%ij" 1413 _, err := ParseQuery(url) 1414 errStr := fmt.Sprint(err) 1415 if !strings.Contains(errStr, "%gh") { 1416 t.Errorf(`ParseQuery(%q) returned error %q, want something containing %q"`, url, errStr, "%gh") 1417 } 1418 } 1419 1420 func TestParseErrors(t *testing.T) { 1421 tests := []struct { 1422 in string 1423 wantErr bool 1424 }{ 1425 {"http://[::1]", false}, 1426 {"http://[::1]:80", false}, 1427 {"http://[::1]:namedport", true}, // rfc3986 3.2.3 1428 {"http://x:namedport", true}, // rfc3986 3.2.3 1429 {"http://[::1]/", false}, 1430 {"http://[::1]a", true}, 1431 {"http://[::1]%23", true}, 1432 {"http://[::1%25en0]", false}, // valid zone id 1433 {"http://[::1]:", false}, // colon, but no port OK 1434 {"http://x:", false}, // colon, but no port OK 1435 {"http://[::1]:%38%30", true}, // not allowed: % encoding only for non-ASCII 1436 {"http://[::1%25%41]", false}, // RFC 6874 allows over-escaping in zone 1437 {"http://[%10::1]", true}, // no %xx escapes in IP address 1438 {"http://[::1]/%48", false}, // %xx in path is fine 1439 {"http://%41:8080/", true}, // not allowed: % encoding only for non-ASCII 1440 {"mysql://x@y(z:123)/foo", false}, // golang.org/issue/12023 1441 {"mysql://x@y(1.2.3.4:123)/foo", false}, 1442 1443 {"http://[]%20%48%54%54%50%2f%31%2e%31%0a%4d%79%48%65%61%64%65%72%3a%20%31%32%33%0a%0a/", true}, // golang.org/issue/11208 1444 {"http://a b.com/", true}, // no space in host name please 1445 {"cache_object://foo", true}, // scheme cannot have _, relative path cannot have : in first segment 1446 {"cache_object:foo", true}, 1447 {"cache_object:foo/bar", true}, 1448 {"cache_object/:foo/bar", false}, 1449 } 1450 for _, tt := range tests { 1451 u, err := Parse(tt.in) 1452 if tt.wantErr { 1453 if err == nil { 1454 t.Errorf("Parse(%q) = %#v; want an error", tt.in, u) 1455 } 1456 continue 1457 } 1458 if err != nil { 1459 t.Logf("Parse(%q) = %v; want no error", tt.in, err) 1460 } 1461 } 1462 } 1463 1464 // Issue 11202 1465 func TestStarRequest(t *testing.T) { 1466 u, err := Parse("*") 1467 if err != nil { 1468 t.Fatal(err) 1469 } 1470 if got, want := u.RequestURI(), "*"; got != want { 1471 t.Errorf("RequestURI = %q; want %q", got, want) 1472 } 1473 } 1474 1475 type shouldEscapeTest struct { 1476 in byte 1477 mode encoding 1478 escape bool 1479 } 1480 1481 var shouldEscapeTests = []shouldEscapeTest{ 1482 // Unreserved characters (§2.3) 1483 {'a', encodePath, false}, 1484 {'a', encodeUserPassword, false}, 1485 {'a', encodeQueryComponent, false}, 1486 {'a', encodeFragment, false}, 1487 {'a', encodeHost, false}, 1488 {'z', encodePath, false}, 1489 {'A', encodePath, false}, 1490 {'Z', encodePath, false}, 1491 {'0', encodePath, false}, 1492 {'9', encodePath, false}, 1493 {'-', encodePath, false}, 1494 {'-', encodeUserPassword, false}, 1495 {'-', encodeQueryComponent, false}, 1496 {'-', encodeFragment, false}, 1497 {'.', encodePath, false}, 1498 {'_', encodePath, false}, 1499 {'~', encodePath, false}, 1500 1501 // User information (§3.2.1) 1502 {':', encodeUserPassword, true}, 1503 {'/', encodeUserPassword, true}, 1504 {'?', encodeUserPassword, true}, 1505 {'@', encodeUserPassword, true}, 1506 {'$', encodeUserPassword, false}, 1507 {'&', encodeUserPassword, false}, 1508 {'+', encodeUserPassword, false}, 1509 {',', encodeUserPassword, false}, 1510 {';', encodeUserPassword, false}, 1511 {'=', encodeUserPassword, false}, 1512 1513 // Host (IP address, IPv6 address, registered name, port suffix; §3.2.2) 1514 {'!', encodeHost, false}, 1515 {'$', encodeHost, false}, 1516 {'&', encodeHost, false}, 1517 {'\'', encodeHost, false}, 1518 {'(', encodeHost, false}, 1519 {')', encodeHost, false}, 1520 {'*', encodeHost, false}, 1521 {'+', encodeHost, false}, 1522 {',', encodeHost, false}, 1523 {';', encodeHost, false}, 1524 {'=', encodeHost, false}, 1525 {':', encodeHost, false}, 1526 {'[', encodeHost, false}, 1527 {']', encodeHost, false}, 1528 {'0', encodeHost, false}, 1529 {'9', encodeHost, false}, 1530 {'A', encodeHost, false}, 1531 {'z', encodeHost, false}, 1532 {'_', encodeHost, false}, 1533 {'-', encodeHost, false}, 1534 {'.', encodeHost, false}, 1535 } 1536 1537 func TestShouldEscape(t *testing.T) { 1538 for _, tt := range shouldEscapeTests { 1539 if shouldEscape(tt.in, tt.mode) != tt.escape { 1540 t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape) 1541 } 1542 } 1543 } 1544 1545 type timeoutError struct { 1546 timeout bool 1547 } 1548 1549 func (e *timeoutError) Error() string { return "timeout error" } 1550 func (e *timeoutError) Timeout() bool { return e.timeout } 1551 1552 type temporaryError struct { 1553 temporary bool 1554 } 1555 1556 func (e *temporaryError) Error() string { return "temporary error" } 1557 func (e *temporaryError) Temporary() bool { return e.temporary } 1558 1559 type timeoutTemporaryError struct { 1560 timeoutError 1561 temporaryError 1562 } 1563 1564 func (e *timeoutTemporaryError) Error() string { return "timeout/temporary error" } 1565 1566 var netErrorTests = []struct { 1567 err error 1568 timeout bool 1569 temporary bool 1570 }{{ 1571 err: &Error{"Get", "http://google.com/", &timeoutError{timeout: true}}, 1572 timeout: true, 1573 temporary: false, 1574 }, { 1575 err: &Error{"Get", "http://google.com/", &timeoutError{timeout: false}}, 1576 timeout: false, 1577 temporary: false, 1578 }, { 1579 err: &Error{"Get", "http://google.com/", &temporaryError{temporary: true}}, 1580 timeout: false, 1581 temporary: true, 1582 }, { 1583 err: &Error{"Get", "http://google.com/", &temporaryError{temporary: false}}, 1584 timeout: false, 1585 temporary: false, 1586 }, { 1587 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: true}}}, 1588 timeout: true, 1589 temporary: true, 1590 }, { 1591 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: true}}}, 1592 timeout: false, 1593 temporary: true, 1594 }, { 1595 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: false}}}, 1596 timeout: true, 1597 temporary: false, 1598 }, { 1599 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: false}}}, 1600 timeout: false, 1601 temporary: false, 1602 }, { 1603 err: &Error{"Get", "http://google.com/", io.EOF}, 1604 timeout: false, 1605 temporary: false, 1606 }} 1607 1608 // Test that url.Error implements net.Error and that it forwards 1609 func TestURLErrorImplementsNetError(t *testing.T) { 1610 for i, tt := range netErrorTests { 1611 err, ok := tt.err.(net.Error) 1612 if !ok { 1613 t.Errorf("%d: %T does not implement net.Error", i+1, tt.err) 1614 continue 1615 } 1616 if err.Timeout() != tt.timeout { 1617 t.Errorf("%d: err.Timeout(): got %v, want %v", i+1, err.Timeout(), tt.timeout) 1618 continue 1619 } 1620 if err.Temporary() != tt.temporary { 1621 t.Errorf("%d: err.Temporary(): got %v, want %v", i+1, err.Temporary(), tt.temporary) 1622 } 1623 } 1624 } 1625 1626 func TestURLHostnameAndPort(t *testing.T) { 1627 tests := []struct { 1628 in string // URL.Host field 1629 host string 1630 port string 1631 }{ 1632 {"foo.com:80", "foo.com", "80"}, 1633 {"foo.com", "foo.com", ""}, 1634 {"foo.com:", "foo.com", ""}, 1635 {"FOO.COM", "FOO.COM", ""}, // no canonicalization 1636 {"1.2.3.4", "1.2.3.4", ""}, 1637 {"1.2.3.4:80", "1.2.3.4", "80"}, 1638 {"[1:2:3:4]", "1:2:3:4", ""}, 1639 {"[1:2:3:4]:80", "1:2:3:4", "80"}, 1640 {"[::1]:80", "::1", "80"}, 1641 {"[::1]", "::1", ""}, 1642 {"[::1]:", "::1", ""}, 1643 {"localhost", "localhost", ""}, 1644 {"localhost:443", "localhost", "443"}, 1645 {"some.super.long.domain.example.org:8080", "some.super.long.domain.example.org", "8080"}, 1646 {"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", "17000"}, 1647 {"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", ""}, 1648 1649 // Ensure that even when not valid, Host is one of "Hostname", 1650 // "Hostname:Port", "[Hostname]" or "[Hostname]:Port". 1651 // See https://golang.org/issue/29098. 1652 {"[google.com]:80", "google.com", "80"}, 1653 {"google.com]:80", "google.com]", "80"}, 1654 {"google.com:80_invalid_port", "google.com:80_invalid_port", ""}, 1655 {"[::1]extra]:80", "::1]extra", "80"}, 1656 {"google.com]extra:extra", "google.com]extra:extra", ""}, 1657 } 1658 for _, tt := range tests { 1659 u := &URL{Host: tt.in} 1660 host, port := u.Hostname(), u.Port() 1661 if host != tt.host { 1662 t.Errorf("Hostname for Host %q = %q; want %q", tt.in, host, tt.host) 1663 } 1664 if port != tt.port { 1665 t.Errorf("Port for Host %q = %q; want %q", tt.in, port, tt.port) 1666 } 1667 } 1668 } 1669 1670 var _ encodingPkg.BinaryMarshaler = (*URL)(nil) 1671 var _ encodingPkg.BinaryUnmarshaler = (*URL)(nil) 1672 1673 func TestJSON(t *testing.T) { 1674 u, err := Parse("https://www.google.com/x?y=z") 1675 if err != nil { 1676 t.Fatal(err) 1677 } 1678 js, err := json.Marshal(u) 1679 if err != nil { 1680 t.Fatal(err) 1681 } 1682 1683 // If only we could implement TextMarshaler/TextUnmarshaler, 1684 // this would work: 1685 // 1686 // if string(js) != strconv.Quote(u.String()) { 1687 // t.Errorf("json encoding: %s\nwant: %s\n", js, strconv.Quote(u.String())) 1688 // } 1689 1690 u1 := new(URL) 1691 err = json.Unmarshal(js, u1) 1692 if err != nil { 1693 t.Fatal(err) 1694 } 1695 if u1.String() != u.String() { 1696 t.Errorf("json decoded to: %s\nwant: %s\n", u1, u) 1697 } 1698 } 1699 1700 func TestGob(t *testing.T) { 1701 u, err := Parse("https://www.google.com/x?y=z") 1702 if err != nil { 1703 t.Fatal(err) 1704 } 1705 var w bytes.Buffer 1706 err = gob.NewEncoder(&w).Encode(u) 1707 if err != nil { 1708 t.Fatal(err) 1709 } 1710 1711 u1 := new(URL) 1712 err = gob.NewDecoder(&w).Decode(u1) 1713 if err != nil { 1714 t.Fatal(err) 1715 } 1716 if u1.String() != u.String() { 1717 t.Errorf("json decoded to: %s\nwant: %s\n", u1, u) 1718 } 1719 } 1720 1721 func TestNilUser(t *testing.T) { 1722 defer func() { 1723 if v := recover(); v != nil { 1724 t.Fatalf("unexpected panic: %v", v) 1725 } 1726 }() 1727 1728 u, err := Parse("http://foo.com/") 1729 1730 if err != nil { 1731 t.Fatalf("parse err: %v", err) 1732 } 1733 1734 if v := u.User.Username(); v != "" { 1735 t.Fatalf("expected empty username, got %s", v) 1736 } 1737 1738 if v, ok := u.User.Password(); v != "" || ok { 1739 t.Fatalf("expected empty password, got %s (%v)", v, ok) 1740 } 1741 1742 if v := u.User.String(); v != "" { 1743 t.Fatalf("expected empty string, got %s", v) 1744 } 1745 } 1746 1747 func TestInvalidUserPassword(t *testing.T) { 1748 _, err := Parse("http://user^:passwo^rd@foo.com/") 1749 if got, wantsub := fmt.Sprint(err), "net/url: invalid userinfo"; !strings.Contains(got, wantsub) { 1750 t.Errorf("error = %q; want substring %q", got, wantsub) 1751 } 1752 } 1753 1754 func TestRejectControlCharacters(t *testing.T) { 1755 tests := []string{ 1756 "http://foo.com/?foo\nbar", 1757 "http\r://foo.com/", 1758 "http://foo\x7f.com/", 1759 } 1760 for _, s := range tests { 1761 _, err := Parse(s) 1762 const wantSub = "net/url: invalid control character in URL" 1763 if got := fmt.Sprint(err); !strings.Contains(got, wantSub) { 1764 t.Errorf("Parse(%q) error = %q; want substring %q", s, got, wantSub) 1765 } 1766 } 1767 1768 // But don't reject non-ASCII CTLs, at least for now: 1769 if _, err := Parse("http://foo.com/ctl\x80"); err != nil { 1770 t.Errorf("error parsing URL with non-ASCII control byte: %v", err) 1771 } 1772 1773 } 1774 1775 var escapeBenchmarks = []struct { 1776 unescaped string 1777 query string 1778 path string 1779 }{ 1780 { 1781 unescaped: "one two", 1782 query: "one+two", 1783 path: "one%20two", 1784 }, 1785 { 1786 unescaped: "Фотки собак", 1787 query: "%D0%A4%D0%BE%D1%82%D0%BA%D0%B8+%D1%81%D0%BE%D0%B1%D0%B0%D0%BA", 1788 path: "%D0%A4%D0%BE%D1%82%D0%BA%D0%B8%20%D1%81%D0%BE%D0%B1%D0%B0%D0%BA", 1789 }, 1790 1791 { 1792 unescaped: "shortrun(break)shortrun", 1793 query: "shortrun%28break%29shortrun", 1794 path: "shortrun%28break%29shortrun", 1795 }, 1796 1797 { 1798 unescaped: "longerrunofcharacters(break)anotherlongerrunofcharacters", 1799 query: "longerrunofcharacters%28break%29anotherlongerrunofcharacters", 1800 path: "longerrunofcharacters%28break%29anotherlongerrunofcharacters", 1801 }, 1802 1803 { 1804 unescaped: strings.Repeat("padded/with+various%characters?that=need$some@escaping+paddedsowebreak/256bytes", 4), 1805 query: strings.Repeat("padded%2Fwith%2Bvarious%25characters%3Fthat%3Dneed%24some%40escaping%2Bpaddedsowebreak%2F256bytes", 4), 1806 path: strings.Repeat("padded%2Fwith+various%25characters%3Fthat=need$some@escaping+paddedsowebreak%2F256bytes", 4), 1807 }, 1808 } 1809 1810 func BenchmarkQueryEscape(b *testing.B) { 1811 for _, tc := range escapeBenchmarks { 1812 b.Run("", func(b *testing.B) { 1813 b.ReportAllocs() 1814 var g string 1815 for i := 0; i < b.N; i++ { 1816 g = QueryEscape(tc.unescaped) 1817 } 1818 b.StopTimer() 1819 if g != tc.query { 1820 b.Errorf("QueryEscape(%q) == %q, want %q", tc.unescaped, g, tc.query) 1821 } 1822 1823 }) 1824 } 1825 } 1826 1827 func BenchmarkPathEscape(b *testing.B) { 1828 for _, tc := range escapeBenchmarks { 1829 b.Run("", func(b *testing.B) { 1830 b.ReportAllocs() 1831 var g string 1832 for i := 0; i < b.N; i++ { 1833 g = PathEscape(tc.unescaped) 1834 } 1835 b.StopTimer() 1836 if g != tc.path { 1837 b.Errorf("PathEscape(%q) == %q, want %q", tc.unescaped, g, tc.path) 1838 } 1839 1840 }) 1841 } 1842 } 1843 1844 func BenchmarkQueryUnescape(b *testing.B) { 1845 for _, tc := range escapeBenchmarks { 1846 b.Run("", func(b *testing.B) { 1847 b.ReportAllocs() 1848 var g string 1849 for i := 0; i < b.N; i++ { 1850 g, _ = QueryUnescape(tc.query) 1851 } 1852 b.StopTimer() 1853 if g != tc.unescaped { 1854 b.Errorf("QueryUnescape(%q) == %q, want %q", tc.query, g, tc.unescaped) 1855 } 1856 1857 }) 1858 } 1859 } 1860 1861 func BenchmarkPathUnescape(b *testing.B) { 1862 for _, tc := range escapeBenchmarks { 1863 b.Run("", func(b *testing.B) { 1864 b.ReportAllocs() 1865 var g string 1866 for i := 0; i < b.N; i++ { 1867 g, _ = PathUnescape(tc.path) 1868 } 1869 b.StopTimer() 1870 if g != tc.unescaped { 1871 b.Errorf("PathUnescape(%q) == %q, want %q", tc.path, g, tc.unescaped) 1872 } 1873 1874 }) 1875 } 1876 }