Source file src/net/url/url_test.go

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

View as plain text