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

View as plain text