Best K6 code snippet using http.URL
url_test.go
Source:url_test.go
...7 "reflect"8 "strings"9 "testing"10)11type URLTest struct {12 in string13 out *URL // expected parse; RawPath="" means same as Path14 roundtrip string // expected result of reserializing the URL; empty means same as "in".15}16var urltests = []URLTest{17 // no path18 {19 "http://www.google.com",20 &URL{21 Scheme: "http",22 Host: "www.google.com",23 },24 "",25 },26 // path27 {28 "http://www.google.com/",29 &URL{30 Scheme: "http",31 Host: "www.google.com",32 Path: "/",33 },34 "",35 },36 // path with hex escaping37 {38 "http://www.google.com/file%20one%26two",39 &URL{40 Scheme: "http",41 Host: "www.google.com",42 Path: "/file one&two",43 RawPath: "/file%20one%26two",44 },45 "",46 },47 // user48 {49 "ftp://webmaster@www.google.com/",50 &URL{51 Scheme: "ftp",52 User: User("webmaster"),53 Host: "www.google.com",54 Path: "/",55 },56 "",57 },58 // escape sequence in username59 {60 "ftp://john%20doe@www.google.com/",61 &URL{62 Scheme: "ftp",63 User: User("john doe"),64 Host: "www.google.com",65 Path: "/",66 },67 "ftp://john%20doe@www.google.com/",68 },69 // query70 {71 "http://www.google.com/?q=go+language",72 &URL{73 Scheme: "http",74 Host: "www.google.com",75 Path: "/",76 RawQuery: "q=go+language",77 },78 "",79 },80 // query with hex escaping: NOT parsed81 {82 "http://www.google.com/?q=go%20language",83 &URL{84 Scheme: "http",85 Host: "www.google.com",86 Path: "/",87 RawQuery: "q=go%20language",88 },89 "",90 },91 // %20 outside query92 {93 "http://www.google.com/a%20b?q=c+d",94 &URL{95 Scheme: "http",96 Host: "www.google.com",97 Path: "/a b",98 RawQuery: "q=c+d",99 },100 "",101 },102 // path without leading /, so no parsing103 {104 "http:www.google.com/?q=go+language",105 &URL{106 Scheme: "http",107 Opaque: "www.google.com/",108 RawQuery: "q=go+language",109 },110 "http:www.google.com/?q=go+language",111 },112 // path without leading /, so no parsing113 {114 "http:%2f%2fwww.google.com/?q=go+language",115 &URL{116 Scheme: "http",117 Opaque: "%2f%2fwww.google.com/",118 RawQuery: "q=go+language",119 },120 "http:%2f%2fwww.google.com/?q=go+language",121 },122 // non-authority with path123 {124 "mailto:/webmaster@golang.org",125 &URL{126 Scheme: "mailto",127 Path: "/webmaster@golang.org",128 },129 "mailto:///webmaster@golang.org", // unfortunate compromise130 },131 // non-authority132 {133 "mailto:webmaster@golang.org",134 &URL{135 Scheme: "mailto",136 Opaque: "webmaster@golang.org",137 },138 "",139 },140 // unescaped :// in query should not create a scheme141 {142 "/foo?query=http://bad",143 &URL{144 Path: "/foo",145 RawQuery: "query=http://bad",146 },147 "",148 },149 // leading // without scheme should create an authority150 {151 "//foo",152 &URL{153 Host: "foo",154 },155 "",156 },157 // leading // without scheme, with userinfo, path, and query158 {159 "//user@foo/path?a=b",160 &URL{161 User: User("user"),162 Host: "foo",163 Path: "/path",164 RawQuery: "a=b",165 },166 "",167 },168 // Three leading slashes isn't an authority, but doesn't return an error.169 // (We can't return an error, as this code is also used via170 // ServeHTTP -> ReadRequest -> Parse, which is arguably a171 // different URL parsing context, but currently shares the172 // same codepath)173 {174 "///threeslashes",175 &URL{176 Path: "///threeslashes",177 },178 "",179 },180 {181 "http://user:password@google.com",182 &URL{183 Scheme: "http",184 User: UserPassword("user", "password"),185 Host: "google.com",186 },187 "http://user:password@google.com",188 },189 // unescaped @ in username should not confuse host190 {191 "http://j@ne:password@google.com",192 &URL{193 Scheme: "http",194 User: UserPassword("j@ne", "password"),195 Host: "google.com",196 },197 "http://j%40ne:password@google.com",198 },199 // unescaped @ in password should not confuse host200 {201 "http://jane:p@ssword@google.com",202 &URL{203 Scheme: "http",204 User: UserPassword("jane", "p@ssword"),205 Host: "google.com",206 },207 "http://jane:p%40ssword@google.com",208 },209 {210 "http://j@ne:password@google.com/p@th?q=@go",211 &URL{212 Scheme: "http",213 User: UserPassword("j@ne", "password"),214 Host: "google.com",215 Path: "/p@th",216 RawQuery: "q=@go",217 },218 "http://j%40ne:password@google.com/p@th?q=@go",219 },220 {221 "http://www.google.com/?q=go+language#foo",222 &URL{223 Scheme: "http",224 Host: "www.google.com",225 Path: "/",226 RawQuery: "q=go+language",227 Fragment: "foo",228 },229 "",230 },231 {232 "http://www.google.com/?q=go+language#foo%26bar",233 &URL{234 Scheme: "http",235 Host: "www.google.com",236 Path: "/",237 RawQuery: "q=go+language",238 Fragment: "foo&bar",239 },240 "http://www.google.com/?q=go+language#foo&bar",241 },242 {243 "file:///home/adg/rabbits",244 &URL{245 Scheme: "file",246 Host: "",247 Path: "/home/adg/rabbits",248 },249 "file:///home/adg/rabbits",250 },251 // "Windows" paths are no exception to the rule.252 // See golang.org/issue/6027, especially comment #9.253 {254 "file:///C:/FooBar/Baz.txt",255 &URL{256 Scheme: "file",257 Host: "",258 Path: "/C:/FooBar/Baz.txt",259 },260 "file:///C:/FooBar/Baz.txt",261 },262 // case-insensitive scheme263 {264 "MaIlTo:webmaster@golang.org",265 &URL{266 Scheme: "mailto",267 Opaque: "webmaster@golang.org",268 },269 "mailto:webmaster@golang.org",270 },271 // Relative path272 {273 "a/b/c",274 &URL{275 Path: "a/b/c",276 },277 "a/b/c",278 },279 // escaped '?' in username and password280 {281 "http://%3Fam:pa%3Fsword@google.com",282 &URL{283 Scheme: "http",284 User: UserPassword("?am", "pa?sword"),285 Host: "google.com",286 },287 "",288 },289 // host subcomponent; IPv4 address in RFC 3986290 {291 "http://192.168.0.1/",292 &URL{293 Scheme: "http",294 Host: "192.168.0.1",295 Path: "/",296 },297 "",298 },299 // host and port subcomponents; IPv4 address in RFC 3986300 {301 "http://192.168.0.1:8080/",302 &URL{303 Scheme: "http",304 Host: "192.168.0.1:8080",305 Path: "/",306 },307 "",308 },309 // host subcomponent; IPv6 address in RFC 3986310 {311 "http://[fe80::1]/",312 &URL{313 Scheme: "http",314 Host: "[fe80::1]",315 Path: "/",316 },317 "",318 },319 // host and port subcomponents; IPv6 address in RFC 3986320 {321 "http://[fe80::1]:8080/",322 &URL{323 Scheme: "http",324 Host: "[fe80::1]:8080",325 Path: "/",326 },327 "",328 },329 // host subcomponent; IPv6 address with zone identifier in RFC 6847330 {331 "http://[fe80::1%25en0]/", // alphanum zone identifier332 &URL{333 Scheme: "http",334 Host: "[fe80::1%en0]",335 Path: "/",336 },337 "",338 },339 // host and port subcomponents; IPv6 address with zone identifier in RFC 6847340 {341 "http://[fe80::1%25en0]:8080/", // alphanum zone identifier342 &URL{343 Scheme: "http",344 Host: "[fe80::1%en0]:8080",345 Path: "/",346 },347 "",348 },349 // host subcomponent; IPv6 address with zone identifier in RFC 6847350 {351 "http://[fe80::1%25%65%6e%301-._~]/", // percent-encoded+unreserved zone identifier352 &URL{353 Scheme: "http",354 Host: "[fe80::1%en01-._~]",355 Path: "/",356 },357 "http://[fe80::1%25en01-._~]/",358 },359 // host and port subcomponents; IPv6 address with zone identifier in RFC 6847360 {361 "http://[fe80::1%25%65%6e%301-._~]:8080/", // percent-encoded+unreserved zone identifier362 &URL{363 Scheme: "http",364 Host: "[fe80::1%en01-._~]:8080",365 Path: "/",366 },367 "http://[fe80::1%25en01-._~]:8080/",368 },369 // alternate escapings of path survive round trip370 {371 "http://rest.rsc.io/foo%2fbar/baz%2Fquux?alt=media",372 &URL{373 Scheme: "http",374 Host: "rest.rsc.io",375 Path: "/foo/bar/baz/quux",376 RawPath: "/foo%2fbar/baz%2Fquux",377 RawQuery: "alt=media",378 },379 "",380 },381 // issue 12036382 {383 "mysql://a,b,c/bar",384 &URL{385 Scheme: "mysql",386 Host: "a,b,c",387 Path: "/bar",388 },389 "",390 },391 // worst case host, still round trips392 {393 "scheme://!$&'()*+,;=hello!:port/path",394 &URL{395 Scheme: "scheme",396 Host: "!$&'()*+,;=hello!:port",397 Path: "/path",398 },399 "",400 },401 // worst case path, still round trips402 {403 "http://host/!$&'()*+,;=:@[hello]",404 &URL{405 Scheme: "http",406 Host: "host",407 Path: "/!$&'()*+,;=:@[hello]",408 RawPath: "/!$&'()*+,;=:@[hello]",409 },410 "",411 },412 // golang.org/issue/5684413 {414 "http://example.com/oid/[order_id]",415 &URL{416 Scheme: "http",417 Host: "example.com",418 Path: "/oid/[order_id]",419 RawPath: "/oid/[order_id]",420 },421 "",422 },423}424// more useful string for debugging than fmt's struct printer425func ufmt(u *URL) string {426 var user, pass interface{}427 if u.User != nil {428 user = u.User.Username()429 if p, ok := u.User.Password(); ok {430 pass = p431 }432 }433 return fmt.Sprintf("opaque=%q, scheme=%q, user=%#v, pass=%#v, host=%q, path=%q, rawpath=%q, rawq=%q, frag=%q",434 u.Opaque, u.Scheme, user, pass, u.Host, u.Path, u.RawPath, u.RawQuery, u.Fragment)435}436func DoTest(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) {437 for _, tt := range tests {438 u, err := parse(tt.in)439 if err != nil {440 t.Errorf("%s(%q) returned error %s", name, tt.in, err)441 continue442 }443 if !reflect.DeepEqual(u, tt.out) {444 t.Errorf("%s(%q):\n\thave %v\n\twant %v\n",445 name, tt.in, ufmt(u), ufmt(tt.out))446 }447 }448}449func BenchmarkString(b *testing.B) {450 b.StopTimer()451 b.ReportAllocs()452 for _, tt := range urltests {453 u, err := Parse(tt.in)454 if err != nil {455 b.Errorf("Parse(%q) returned error %s", tt.in, err)456 continue457 }458 if tt.roundtrip == "" {459 continue460 }461 b.StartTimer()462 var g string463 for i := 0; i < b.N; i++ {464 g = u.String()465 }466 b.StopTimer()467 if w := tt.roundtrip; g != w {468 b.Errorf("Parse(%q).String() == %q, want %q", tt.in, g, w)469 }470 }471}472func TestParse(t *testing.T) {473 DoTest(t, Parse, "Parse", urltests)474}475const pathThatLooksSchemeRelative = "//not.a.user@not.a.host/just/a/path"476var parseRequestURLTests = []struct {477 url string478 expectedValid bool479}{480 {"http://foo.com", true},481 {"http://foo.com/", true},482 {"http://foo.com/path", true},483 {"/", true},484 {pathThatLooksSchemeRelative, true},485 {"//not.a.user@%66%6f%6f.com/just/a/path/also", true},486 {"*", true},487 {"http://192.168.0.1/", true},488 {"http://192.168.0.1:8080/", true},489 {"http://[fe80::1]/", true},490 {"http://[fe80::1]:8080/", true},491 // Tests exercising RFC 6874 compliance:492 {"http://[fe80::1%25en0]/", true}, // with alphanum zone identifier493 {"http://[fe80::1%25en0]:8080/", true}, // with alphanum zone identifier494 {"http://[fe80::1%25%65%6e%301-._~]/", true}, // with percent-encoded+unreserved zone identifier495 {"http://[fe80::1%25%65%6e%301-._~]:8080/", true}, // with percent-encoded+unreserved zone identifier496 {"foo.html", false},497 {"../dir/", false},498 {"http://192.168.0.%31/", false},499 {"http://192.168.0.%31:8080/", false},500 {"http://[fe80::%31]/", false},501 {"http://[fe80::%31]:8080/", false},502 {"http://[fe80::%31%25en0]/", false},503 {"http://[fe80::%31%25en0]:8080/", false},504 // These two cases are valid as textual representations as505 // described in RFC 4007, but are not valid as address506 // literals with IPv6 zone identifiers in URIs as described in507 // RFC 6874.508 {"http://[fe80::1%en0]/", false},509 {"http://[fe80::1%en0]:8080/", false},510}511func TestParseRequestURI(t *testing.T) {512 for _, test := range parseRequestURLTests {513 _, err := ParseRequestURI(test.url)514 valid := err == nil515 if valid != test.expectedValid {516 t.Errorf("Expected valid=%v for %q; got %v", test.expectedValid, test.url, valid)517 }518 }519 url, err := ParseRequestURI(pathThatLooksSchemeRelative)520 if err != nil {521 t.Fatalf("Unexpected error %v", err)522 }523 if url.Path != pathThatLooksSchemeRelative {524 t.Errorf("Expected path %q; got %q", pathThatLooksSchemeRelative, url.Path)525 }526}527func DoTestString(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) {528 for _, tt := range tests {529 u, err := parse(tt.in)530 if err != nil {531 t.Errorf("%s(%q) returned error %s", name, tt.in, err)532 continue533 }534 expected := tt.in535 if len(tt.roundtrip) > 0 {536 expected = tt.roundtrip537 }538 s := u.String()539 if s != expected {540 t.Errorf("%s(%q).String() == %q (expected %q)", name, tt.in, s, expected)541 }542 }543}544func TestURLString(t *testing.T) {545 DoTestString(t, Parse, "Parse", urltests)546 // no leading slash on path should prepend547 // slash on String() call548 noslash := URLTest{549 "http://www.google.com/search",550 &URL{551 Scheme: "http",552 Host: "www.google.com",553 Path: "search",554 },555 "",556 }557 s := noslash.out.String()558 if s != noslash.in {559 t.Errorf("Expected %s; go %s", noslash.in, s)560 }561}562type EscapeTest struct {563 in string564 out string565 err error566}567var unescapeTests = []EscapeTest{568 {569 "",570 "",571 nil,572 },573 {574 "abc",575 "abc",576 nil,577 },578 {579 "1%41",580 "1A",581 nil,582 },583 {584 "1%41%42%43",585 "1ABC",586 nil,587 },588 {589 "%4a",590 "J",591 nil,592 },593 {594 "%6F",595 "o",596 nil,597 },598 {599 "%", // not enough characters after %600 "",601 EscapeError("%"),602 },603 {604 "%a", // not enough characters after %605 "",606 EscapeError("%a"),607 },608 {609 "%1", // not enough characters after %610 "",611 EscapeError("%1"),612 },613 {614 "123%45%6", // not enough characters after %615 "",616 EscapeError("%6"),617 },618 {619 "%zzzzz", // invalid hex digits620 "",621 EscapeError("%zz"),622 },623}624func TestUnescape(t *testing.T) {625 for _, tt := range unescapeTests {626 actual, err := QueryUnescape(tt.in)627 if actual != tt.out || (err != nil) != (tt.err != nil) {628 t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err)629 }630 }631}632var escapeTests = []EscapeTest{633 {634 "",635 "",636 nil,637 },638 {639 "abc",640 "abc",641 nil,642 },643 {644 "one two",645 "one+two",646 nil,647 },648 {649 "10%",650 "10%25",651 nil,652 },653 {654 " ?&=#+%!<>#\"{}|\\^[]`âº\t:/@$'()*,;",655 "+%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",656 nil,657 },658}659func TestEscape(t *testing.T) {660 for _, tt := range escapeTests {661 actual := QueryEscape(tt.in)662 if tt.out != actual {663 t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out)664 }665 // for bonus points, verify that escape:unescape is an identity.666 roundtrip, err := QueryUnescape(actual)667 if roundtrip != tt.in || err != nil {668 t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")669 }670 }671}672//var userinfoTests = []UserinfoTest{673// {"user", "password", "user:password"},674// {"foo:bar", "~!@#$%^&*()_+{}|[]\\-=`:;'\"<>?,./",675// "foo%3Abar:~!%40%23$%25%5E&*()_+%7B%7D%7C%5B%5D%5C-=%60%3A;'%22%3C%3E?,.%2F"},676//}677type EncodeQueryTest struct {678 m Values679 expected string680}681var encodeQueryTests = []EncodeQueryTest{682 {nil, ""},683 {Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"},684 {Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"},685 {Values{686 "a": {"a1", "a2", "a3"},687 "b": {"b1", "b2", "b3"},688 "c": {"c1", "c2", "c3"},689 }, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"},690}691func TestEncodeQuery(t *testing.T) {692 for _, tt := range encodeQueryTests {693 if q := tt.m.Encode(); q != tt.expected {694 t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected)695 }696 }697}698var resolvePathTests = []struct {699 base, ref, expected string700}{701 {"a/b", ".", "/a/"},702 {"a/b", "c", "/a/c"},703 {"a/b", "..", "/"},704 {"a/", "..", "/"},705 {"a/", "../..", "/"},706 {"a/b/c", "..", "/a/"},707 {"a/b/c", "../d", "/a/d"},708 {"a/b/c", ".././d", "/a/d"},709 {"a/b", "./..", "/"},710 {"a/./b", ".", "/a/"},711 {"a/../", ".", "/"},712 {"a/.././b", "c", "/c"},713}714func TestResolvePath(t *testing.T) {715 for _, test := range resolvePathTests {716 got := resolvePath(test.base, test.ref)717 if got != test.expected {718 t.Errorf("For %q + %q got %q; expected %q", test.base, test.ref, got, test.expected)719 }720 }721}722var resolveReferenceTests = []struct {723 base, rel, expected string724}{725 // Absolute URL references726 {"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"},727 {"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"},728 {"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"},729 // Path-absolute references730 {"http://foo.com/bar", "/baz", "http://foo.com/baz"},731 {"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"},732 {"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"},733 // Scheme-relative734 {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"},735 // Path-relative references:736 // ... current directory737 {"http://foo.com", ".", "http://foo.com/"},738 {"http://foo.com/bar", ".", "http://foo.com/"},739 {"http://foo.com/bar/", ".", "http://foo.com/bar/"},740 // ... going down741 {"http://foo.com", "bar", "http://foo.com/bar"},742 {"http://foo.com/", "bar", "http://foo.com/bar"},743 {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"},744 // ... going up745 {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"},746 {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"},747 {"http://foo.com/bar", "..", "http://foo.com/"},748 {"http://foo.com/bar/baz", "./..", "http://foo.com/"},749 // ".." in the middle (issue 3560)750 {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"},751 {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"},752 {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"},753 {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"},754 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"},755 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"},756 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"},757 {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"},758 // Remove any dot-segments prior to forming the target URI.759 // http://tools.ietf.org/html/rfc3986#section-5.2.4760 {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"},761 // Triple dot isn't special762 {"http://foo.com/bar", "...", "http://foo.com/..."},763 // Fragment764 {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"},765 // RFC 3986: Normal Examples766 // http://tools.ietf.org/html/rfc3986#section-5.4.1767 {"http://a/b/c/d;p?q", "g:h", "g:h"},768 {"http://a/b/c/d;p?q", "g", "http://a/b/c/g"},769 {"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"},770 {"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"},771 {"http://a/b/c/d;p?q", "/g", "http://a/g"},772 {"http://a/b/c/d;p?q", "//g", "http://g"},773 {"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"},774 {"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"},775 {"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"},776 {"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"},777 {"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"},778 {"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"},779 {"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"},780 {"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"},781 {"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"},782 {"http://a/b/c/d;p?q", ".", "http://a/b/c/"},783 {"http://a/b/c/d;p?q", "./", "http://a/b/c/"},784 {"http://a/b/c/d;p?q", "..", "http://a/b/"},785 {"http://a/b/c/d;p?q", "../", "http://a/b/"},786 {"http://a/b/c/d;p?q", "../g", "http://a/b/g"},787 {"http://a/b/c/d;p?q", "../..", "http://a/"},788 {"http://a/b/c/d;p?q", "../../", "http://a/"},789 {"http://a/b/c/d;p?q", "../../g", "http://a/g"},790 // RFC 3986: Abnormal Examples791 // http://tools.ietf.org/html/rfc3986#section-5.4.2792 {"http://a/b/c/d;p?q", "../../../g", "http://a/g"},793 {"http://a/b/c/d;p?q", "../../../../g", "http://a/g"},794 {"http://a/b/c/d;p?q", "/./g", "http://a/g"},795 {"http://a/b/c/d;p?q", "/../g", "http://a/g"},796 {"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."},797 {"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"},798 {"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."},799 {"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"},800 {"http://a/b/c/d;p?q", "./../g", "http://a/b/g"},801 {"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"},802 {"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"},803 {"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"},804 {"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"},805 {"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"},806 {"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"},807 {"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"},808 {"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"},809 {"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"},810 // Extras.811 {"https://a/b/c/d;p?q", "//g?q", "https://g?q"},812 {"https://a/b/c/d;p?q", "//g#s", "https://g#s"},813 {"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"},814 {"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"},815 {"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"},816}817func TestResolveReference(t *testing.T) {818 mustParse := func(url string) *URL {819 u, err := Parse(url)820 if err != nil {821 t.Fatalf("Expected URL to parse: %q, got error: %v", url, err)822 }823 return u824 }825 opaque := &URL{Scheme: "scheme", Opaque: "opaque"}826 for _, test := range resolveReferenceTests {827 base := mustParse(test.base)828 rel := mustParse(test.rel)829 url := base.ResolveReference(rel)830 if url.String() != test.expected {831 t.Errorf("URL(%q).ResolveReference(%q) == %q, got %q", test.base, test.rel, test.expected, url.String())832 }833 // Ensure that new instances are returned.834 if base == url {835 t.Errorf("Expected URL.ResolveReference to return new URL instance.")836 }837 // Test the convenience wrapper too.838 url, err := base.Parse(test.rel)839 if err != nil {840 t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err)841 } else if url.String() != test.expected {842 t.Errorf("URL(%q).Parse(%q) == %q, got %q", test.base, test.rel, test.expected, url.String())843 } else if base == url {844 // Ensure that new instances are returned for the wrapper too.845 t.Errorf("Expected URL.Parse to return new URL instance.")846 }847 // Ensure Opaque resets the URL.848 url = base.ResolveReference(opaque)849 if *url != *opaque {850 t.Errorf("ResolveReference failed to resolve opaque URL: want %#v, got %#v", url, opaque)851 }852 // Test the convenience wrapper with an opaque URL too.853 url, err = base.Parse("scheme:opaque")854 if err != nil {855 t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err)856 } else if *url != *opaque {857 t.Errorf("Parse failed to resolve opaque URL: want %#v, got %#v", url, opaque)858 } else if base == url {859 // Ensure that new instances are returned, again.860 t.Errorf("Expected URL.Parse to return new URL instance.")861 }862 }863}864func TestQueryValues(t *testing.T) {865 u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2")866 v := u.Query()867 if len(v) != 2 {868 t.Errorf("got %d keys in Query values, want 2", len(v))869 }870 if g, e := v.Get("foo"), "bar"; g != e {871 t.Errorf("Get(foo) = %q, want %q", g, e)872 }873 // Case sensitive:874 if g, e := v.Get("Foo"), ""; g != e {875 t.Errorf("Get(Foo) = %q, want %q", g, e)876 }877 if g, e := v.Get("bar"), "1"; g != e {878 t.Errorf("Get(bar) = %q, want %q", g, e)879 }880 if g, e := v.Get("baz"), ""; g != e {881 t.Errorf("Get(baz) = %q, want %q", g, e)882 }883 v.Del("bar")884 if g, e := v.Get("bar"), ""; g != e {885 t.Errorf("second Get(bar) = %q, want %q", g, e)886 }887}888type parseTest struct {889 query string890 out Values891}892var parseTests = []parseTest{893 {894 query: "a=1&b=2",895 out: Values{"a": []string{"1"}, "b": []string{"2"}},896 },897 {898 query: "a=1&a=2&a=banana",899 out: Values{"a": []string{"1", "2", "banana"}},900 },901 {902 query: "ascii=%3Ckey%3A+0x90%3E",903 out: Values{"ascii": []string{"<key: 0x90>"}},904 },905 {906 query: "a=1;b=2",907 out: Values{"a": []string{"1"}, "b": []string{"2"}},908 },909 {910 query: "a=1&a=2;a=banana",911 out: Values{"a": []string{"1", "2", "banana"}},912 },913}914func TestParseQuery(t *testing.T) {915 for i, test := range parseTests {916 form, err := ParseQuery(test.query)917 if err != nil {918 t.Errorf("test %d: Unexpected error: %v", i, err)919 continue920 }921 if len(form) != len(test.out) {922 t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))923 }924 for k, evs := range test.out {925 vs, ok := form[k]926 if !ok {927 t.Errorf("test %d: Missing key %q", i, k)928 continue929 }930 if len(vs) != len(evs) {931 t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))932 continue933 }934 for j, ev := range evs {935 if v := vs[j]; v != ev {936 t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)937 }938 }939 }940 }941}942type RequestURITest struct {943 url *URL944 out string945}946var requritests = []RequestURITest{947 {948 &URL{949 Scheme: "http",950 Host: "example.com",951 Path: "",952 },953 "/",954 },955 {956 &URL{957 Scheme: "http",958 Host: "example.com",959 Path: "/a b",960 },961 "/a%20b",962 },963 // golang.org/issue/4860 variant 1964 {965 &URL{966 Scheme: "http",967 Host: "example.com",968 Opaque: "/%2F/%2F/",969 },970 "/%2F/%2F/",971 },972 // golang.org/issue/4860 variant 2973 {974 &URL{975 Scheme: "http",976 Host: "example.com",977 Opaque: "//other.example.com/%2F/%2F/",978 },979 "http://other.example.com/%2F/%2F/",980 },981 // better fix for issue 4860982 {983 &URL{984 Scheme: "http",985 Host: "example.com",986 Path: "/////",987 RawPath: "/%2F/%2F/",988 },989 "/%2F/%2F/",990 },991 {992 &URL{993 Scheme: "http",994 Host: "example.com",995 Path: "/////",996 RawPath: "/WRONG/", // ignored because doesn't match Path997 },998 "/////",999 },1000 {1001 &URL{1002 Scheme: "http",1003 Host: "example.com",1004 Path: "/a b",1005 RawQuery: "q=go+language",1006 },1007 "/a%20b?q=go+language",1008 },1009 {1010 &URL{1011 Scheme: "http",1012 Host: "example.com",1013 Path: "/a b",1014 RawPath: "/a b", // ignored because invalid1015 RawQuery: "q=go+language",1016 },1017 "/a%20b?q=go+language",1018 },1019 {1020 &URL{1021 Scheme: "http",1022 Host: "example.com",1023 Path: "/a?b",1024 RawPath: "/a?b", // ignored because invalid1025 RawQuery: "q=go+language",1026 },1027 "/a%3Fb?q=go+language",1028 },1029 {1030 &URL{1031 Scheme: "myschema",1032 Opaque: "opaque",1033 },1034 "opaque",1035 },1036 {1037 &URL{1038 Scheme: "myschema",1039 Opaque: "opaque",1040 RawQuery: "q=go+language",1041 },1042 "opaque?q=go+language",1043 },1044}1045func TestRequestURI(t *testing.T) {1046 for _, tt := range requritests {1047 s := tt.url.RequestURI()1048 if s != tt.out {1049 t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out)1050 }1051 }...
auth_server.go
Source:auth_server.go
...21const HTTP_QUERY_KEY = "key"22const HTTP_QUERY_USERNAME = "username"23const HTTP_QUERY_CLIENT_IP = "ip"24const HTTP_QUERY_CLIENT_MAC = "mac"25const HTTP_QUERY_CLIENT_ORIGINAL_URL = "url"26const HTTP_QUERY_STAGE = "stage"27const AUTH_STAGE_LOGIN = "login"28const AUTH_STAGE_LOGOUT = "logout"29const AUTH_SERVER_STATUS_NORMAL = "Pong"30const AUTH_SERVER_TOKEN_INVALID = "Auth: 0"31const AUTH_SERVER_TOKEN_VALID_STANDARD_USER = "Auth: 1"32const AUTH_SERVER_TOKEN_VALID_GUEST_USER = "Auth: 2"33type ServerUrl struct {34 PingPage string35 LoginPage string36 PortalPage string37 AuthPage string38 AddUserPage string39 OnlineListPage string40 KickOutUserPage string41}42var serverUrl ServerUrl43type GetRequestFunc func(url string) ([]byte, error)44type PostRequestFunc func(url string, data []byte) ([]byte, error)45var DoGetRequest GetRequestFunc46var DoPostRequest PostRequestFunc47func Init(authServer config.AuthServer) error {48 SetServerUrl(authServer)49 if authServer.SSLOn {50 DoGetRequest = httpsGetRequest51 DoPostRequest = httpsPostRequest52 } else {53 DoGetRequest = httpGetRequest54 DoPostRequest = httpPostRequest55 }56 err := CheckStatus()57 if err != nil {58 return err59 }60 //RestoreOnlineUser()61 return nil62}63func httpsGetRequest(url string) ([]byte, error) {64 tr := http.Transport{65 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},66 }67 client := http.Client{68 Transport: &tr,69 }70 req, err := http.NewRequest("GET", url, nil)71 if err != nil {72 return nil, err73 }74 resp, err := client.Do(req)75 if err != nil {76 return nil, err77 }78 body, err := ioutil.ReadAll(resp.Body)79 if err != nil {80 return nil, err81 }82 defer resp.Body.Close()83 return body, nil84}85func httpGetRequest(url string) ([]byte, error) {86 client := http.Client{}87 req, err := http.NewRequest("GET", url, nil)88 if err != nil {89 return nil, err90 }91 resp, err := client.Do(req)92 if err != nil {93 return nil, err94 }95 body, err := ioutil.ReadAll(resp.Body)96 if err != nil {97 return nil, err98 }99 defer resp.Body.Close()100 return body, nil101}102func httpsPostRequest(url string, data []byte) ([]byte, error) {103 tr := http.Transport{104 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},105 }106 client := http.Client{107 Transport: &tr,108 }109 var buffer *bytes.Buffer110 var req *http.Request111 var err error112 if data != nil {113 req, err = http.NewRequest("POST", url, buffer)114 } else {115 req, err = http.NewRequest("POST", url, nil)116 }117 if err != nil {118 return nil, err119 }120 resp, err := client.Do(req)121 if err != nil {122 return nil, err123 }124 body, err := ioutil.ReadAll(resp.Body)125 if err != nil {126 return nil, err127 }128 defer resp.Body.Close()129 return body, nil130}131func httpPostRequest(url string, data []byte) ([]byte, error) {132 client := http.Client{}133 var req *http.Request134 var err error135 if data != nil {136 req, err = http.NewRequest("POST", url, bytes.NewBuffer(data))137 } else {138 req, err = http.NewRequest("POST", url, nil)139 }140 if err != nil {141 return nil, err142 }143 resp, err := client.Do(req)144 if err != nil {145 return nil, err146 }147 body, err := ioutil.ReadAll(resp.Body)148 if err != nil {149 return nil, err150 }151 defer resp.Body.Close()152 return body, nil153}154func SetServerUrl(AuthServer config.AuthServer) {155 var base string156 if AuthServer.SSLOn {157 base = "https://" + AuthServer.Host + ":" + AuthServer.Port + AuthServer.RootPath158 } else {159 base = "http://" + AuthServer.Host + ":" + AuthServer.Port + AuthServer.RootPath160 }161 serverUrl.PingPage = base + AuthServer.PingPath162 serverUrl.LoginPage = base + AuthServer.LoginPath163 serverUrl.AuthPage = base + AuthServer.AuthPath164 serverUrl.PortalPage = base + AuthServer.PortalPath165 serverUrl.AddUserPage = base + AuthServer.AddUserPath166 serverUrl.OnlineListPage = base + AuthServer.OnlineListPath167 serverUrl.KickOutUserPage = base + AuthServer.KickOutUserPath168}169func CheckStatus() error {170 data, err := DoGetRequest(serverUrl.PingPage)171 if err != nil {172 return err173 }174 if string(data) != AUTH_SERVER_STATUS_NORMAL {175 return errors.New("auth server offline: " + string(data))176 }177 return nil178}179func VerifyToken(token, clientMac, clientIP, stage string) (int, error) {180 authUrl := FillAuthPageParam(token, clientMac, clientIP, stage)181 log.Println(authUrl)182 data, err := DoGetRequest(authUrl)183 if err != nil {184 return 0, err185 }186 if string(data) == AUTH_SERVER_TOKEN_INVALID {187 return 0, errors.New("token is invalid: " + string(data))188 }189 if string(data) == AUTH_SERVER_TOKEN_VALID_STANDARD_USER {190 return 1, nil191 }192 if string(data) == AUTH_SERVER_TOKEN_VALID_GUEST_USER {193 return 2, nil194 }195 return 0, errors.New("unknown error")196}197func Update(config config.AuthServer) error {198 SetServerUrl(config)199 return nil200}201func FillLoginPageParam(gwId, gwIP, gwPort, gwSSLOn, clientMac, clientIP, originUrl string) string {202 url :=203 fmt.Sprintf(`%s?%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s`,204 serverUrl.LoginPage,205 HTTP_QUERY_GW_ID, gwId, HTTP_QUERY_GW_IP, gwIP, HTTP_QUERY_GW_PORT, gwPort, HTTP_QUERY_GW_SSL_ON, gwSSLOn,206 HTTP_QUERY_CLIENT_MAC, clientMac, HTTP_QUERY_CLIENT_IP, clientIP, HTTP_QUERY_CLIENT_ORIGINAL_URL, originUrl,207 )208 return url209}210func FillAuthPageParam(token, clientMac, clientIP, stage string) string {211 url := fmt.Sprintf(`%s?%s=%s&%s=%s&%s=%s&%s=%s`,212 serverUrl.AuthPage, HTTP_QUERY_TOKEN, token, HTTP_QUERY_CLIENT_MAC, clientMac,213 HTTP_QUERY_CLIENT_IP, clientIP, HTTP_QUERY_STAGE, stage,214 )215 return url216}217func FillPortalPageParam(clientMac, clientIP, originUrl string) string {218 url := fmt.Sprintf(`%s?%s=%s&%s=%s&%s=%s`,219 serverUrl.PortalPage, HTTP_QUERY_CLIENT_MAC, clientMac, HTTP_QUERY_CLIENT_IP,220 clientIP, HTTP_QUERY_CLIENT_ORIGINAL_URL, originUrl,221 )222 return url223}224func FillAddUserPageParam(key string) string {225 url := fmt.Sprintf(`%s?%s=%s`,226 serverUrl.AddUserPage, HTTP_QUERY_KEY, key,227 )228 return url229}230func FillOnlineListPageParam(key string) string {231 url := fmt.Sprintf(`%s?%s=%s`,232 serverUrl.OnlineListPage, HTTP_QUERY_KEY, key,233 )234 return url...
URL
Using AI Code Generation
1func main() {2 if err != nil {3 log.Fatal(err)4 }5 defer resp.Body.Close()6 body, err := ioutil.ReadAll(resp.Body)7 if err != nil {8 log.Fatal(err)9 }10 fmt.Printf("%s", body)11}12func main() {13 if err != nil {14 log.Fatal(err)15 }16 client := &http.Client{}17 resp, err := client.Do(req)18 if err != nil {19 log.Fatal(err)20 }21 defer resp.Body.Close()22 body, err := ioutil.ReadAll(resp.Body)23 if err != nil {24 log.Fatal(err)25 }26 fmt.Printf("%s", body)27}28func main() {29 client := &http.Client{}30 if err != nil {31 log.Fatal(err)32 }33 defer resp.Body.Close()34 body, err := ioutil.ReadAll(resp.Body)35 if err != nil {36 log.Fatal(err)37 }38 fmt.Printf("%s", body)39}40func main() {41 client := &http.Client{}42 if err != nil {43 log.Fatal(err)44 }45 resp, err := client.Do(req)46 if err != nil {47 log.Fatal(err)48 }49 defer resp.Body.Close()50 body, err := ioutil.ReadAll(resp.Body)51 if err != nil {52 log.Fatal(err)53 }54 fmt.Printf("%s", body)55}56func main() {57 client := &http.Client{}58 if err != nil {59 log.Fatal(err)60 }61 defer resp.Body.Close()62 body, err := ioutil.ReadAll(resp.Body)63 if err != nil {64 log.Fatal(err)65 }66 fmt.Printf("%s", body)67}
URL
Using AI Code Generation
1import (2func main() {3 resp, err := http.Get(url)4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Response Status:", resp.Status)8 fmt.Println("Response Headers:", resp.Header)9}
URL
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Printf("Error: %s5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Printf("Error: %s10 }11 fmt.Printf("%s12}
URL
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("Error:", err)5 }6 fmt.Println("Response:", resp)7}
URL
Using AI Code Generation
1import (2func main() {3 fmt.Println("URL is", url)4 response, err := http.Get(url)5 if err != nil {6 fmt.Println(err)7 } else {8 fmt.Println("Response is", response)9 }10}11Response is &{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=ISO-8859-1] Date:[Mon, 15 Feb 2021 09:30:57 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2021-02-15-09; expires=Wed, 17-Mar-2021 09:30:57 GMT; path=/; domain=.google.com, NID=207=IcTtPzGtP4X2Z4Jg1x4tR0cNwA2QrQbW8gFyLh9Zp0XZ1l3q8jv0C3mU7VY0DmLW7VvzO1ZU5BZf6X5W8xvQ6BwYV7lYB6W5l7Jvz1U5BZf6X5W8xvQ6BwYV7lYB6W5l7Jvz1U5BZf6X5W8xvQ6BwYV7lYB6W5l7Jvz1U5BZf6X5W8xvQ6BwYV7lYB6W5l7Jvz1U5BZf6X5W8xvQ6BwYV7lYB6W5l7Jvz1U5BZf6X5W8xvQ6BwYV7lYB6W5l7Jvz1U5BZf6X5W8xvQ6BwYV7lYB6W5l
URL
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("error")5 }6 fmt.Println(u)7}8&{200 OK 200 HTTP/1.1 1 1 map[Age:[0] Cache-Control:[private, max-age=0] Content-Type:[text/html; charset=ISO-8859-1] Date:[Wed, 01 Apr 2020 17:33:25 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2020-04-01-17
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!