How to use match method of http Package

Best K6 code snippet using http.match

mux_test.go

Source:mux_test.go Github

copy

Full Screen

...11type routeTest struct {12 title string // title of the test13 route *Route // the route being tested14 request *http.Request // a request to test the route15 vars map[string]string // the expected vars of the match16 host string // the expected host of the match17 path string // the expected path of the match18 shouldMatch bool // whether the request is expected to match the route at all19 shouldRedirect bool // whether the request should result in a redirect20}21func TestHost(t *testing.T) {22 // newRequestHost a new request with a method, url, and host header23 newRequestHost := func(method, url, host string) *http.Request {24 req, err := http.NewRequest(method, url, nil)25 if err != nil {26 panic(err)27 }28 req.Host = host29 return req30 }31 tests := []routeTest{32 {33 title: "Host route match",34 route: new(Route).Host("aaa.bbb.ccc"),35 request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),36 vars: map[string]string{},37 host: "aaa.bbb.ccc",38 path: "",39 shouldMatch: true,40 },41 {42 title: "Host route, wrong host in request URL",43 route: new(Route).Host("aaa.bbb.ccc"),44 request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),45 vars: map[string]string{},46 host: "aaa.bbb.ccc",47 path: "",48 shouldMatch: false,49 },50 {51 title: "Host route with port, match",52 route: new(Route).Host("aaa.bbb.ccc:1234"),53 request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"),54 vars: map[string]string{},55 host: "aaa.bbb.ccc:1234",56 path: "",57 shouldMatch: true,58 },59 {60 title: "Host route with port, wrong port in request URL",61 route: new(Route).Host("aaa.bbb.ccc:1234"),62 request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"),63 vars: map[string]string{},64 host: "aaa.bbb.ccc:1234",65 path: "",66 shouldMatch: false,67 },68 {69 title: "Host route, match with host in request header",70 route: new(Route).Host("aaa.bbb.ccc"),71 request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"),72 vars: map[string]string{},73 host: "aaa.bbb.ccc",74 path: "",75 shouldMatch: true,76 },77 {78 title: "Host route, wrong host in request header",79 route: new(Route).Host("aaa.bbb.ccc"),80 request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"),81 vars: map[string]string{},82 host: "aaa.bbb.ccc",83 path: "",84 shouldMatch: false,85 },86 // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true},87 {88 title: "Host route with port, wrong host in request header",89 route: new(Route).Host("aaa.bbb.ccc:1234"),90 request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"),91 vars: map[string]string{},92 host: "aaa.bbb.ccc:1234",93 path: "",94 shouldMatch: false,95 },96 {97 title: "Host route with pattern, match",98 route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),99 request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),100 vars: map[string]string{"v1": "bbb"},101 host: "aaa.bbb.ccc",102 path: "",103 shouldMatch: true,104 },105 {106 title: "Host route with pattern, wrong host in request URL",107 route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),108 request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),109 vars: map[string]string{"v1": "bbb"},110 host: "aaa.bbb.ccc",111 path: "",112 shouldMatch: false,113 },114 {115 title: "Host route with multiple patterns, match",116 route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),117 request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),118 vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},119 host: "aaa.bbb.ccc",120 path: "",121 shouldMatch: true,122 },123 {124 title: "Host route with multiple patterns, wrong host in request URL",125 route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),126 request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),127 vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},128 host: "aaa.bbb.ccc",129 path: "",130 shouldMatch: false,131 },132 }133 for _, test := range tests {134 testRoute(t, test)135 }136}137func TestPath(t *testing.T) {138 tests := []routeTest{139 {140 title: "Path route, match",141 route: new(Route).Path("/111/222/333"),142 request: newRequest("GET", "http://localhost/111/222/333"),143 vars: map[string]string{},144 host: "",145 path: "/111/222/333",146 shouldMatch: true,147 },148 {149 title: "Path route, match with trailing slash in request and path",150 route: new(Route).Path("/111/"),151 request: newRequest("GET", "http://localhost/111/"),152 vars: map[string]string{},153 host: "",154 path: "/111/",155 shouldMatch: true,156 },157 {158 title: "Path route, do not match with trailing slash in path",159 route: new(Route).Path("/111/"),160 request: newRequest("GET", "http://localhost/111"),161 vars: map[string]string{},162 host: "",163 path: "/111",164 shouldMatch: false,165 },166 {167 title: "Path route, do not match with trailing slash in request",168 route: new(Route).Path("/111"),169 request: newRequest("GET", "http://localhost/111/"),170 vars: map[string]string{},171 host: "",172 path: "/111/",173 shouldMatch: false,174 },175 {176 title: "Path route, wrong path in request in request URL",177 route: new(Route).Path("/111/222/333"),178 request: newRequest("GET", "http://localhost/1/2/3"),179 vars: map[string]string{},180 host: "",181 path: "/111/222/333",182 shouldMatch: false,183 },184 {185 title: "Path route with pattern, match",186 route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),187 request: newRequest("GET", "http://localhost/111/222/333"),188 vars: map[string]string{"v1": "222"},189 host: "",190 path: "/111/222/333",191 shouldMatch: true,192 },193 {194 title: "Path route with pattern, URL in request does not match",195 route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),196 request: newRequest("GET", "http://localhost/111/aaa/333"),197 vars: map[string]string{"v1": "222"},198 host: "",199 path: "/111/222/333",200 shouldMatch: false,201 },202 {203 title: "Path route with multiple patterns, match",204 route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),205 request: newRequest("GET", "http://localhost/111/222/333"),206 vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},207 host: "",208 path: "/111/222/333",209 shouldMatch: true,210 },211 {212 title: "Path route with multiple patterns, URL in request does not match",213 route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),214 request: newRequest("GET", "http://localhost/111/aaa/333"),215 vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},216 host: "",217 path: "/111/222/333",218 shouldMatch: false,219 },220 }221 for _, test := range tests {222 testRoute(t, test)223 }224}225func TestPathPrefix(t *testing.T) {226 tests := []routeTest{227 {228 title: "PathPrefix route, match",229 route: new(Route).PathPrefix("/111"),230 request: newRequest("GET", "http://localhost/111/222/333"),231 vars: map[string]string{},232 host: "",233 path: "/111",234 shouldMatch: true,235 },236 {237 title: "PathPrefix route, match substring",238 route: new(Route).PathPrefix("/1"),239 request: newRequest("GET", "http://localhost/111/222/333"),240 vars: map[string]string{},241 host: "",242 path: "/1",243 shouldMatch: true,244 },245 {246 title: "PathPrefix route, URL prefix in request does not match",247 route: new(Route).PathPrefix("/111"),248 request: newRequest("GET", "http://localhost/1/2/3"),249 vars: map[string]string{},250 host: "",251 path: "/111",252 shouldMatch: false,253 },254 {255 title: "PathPrefix route with pattern, match",256 route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),257 request: newRequest("GET", "http://localhost/111/222/333"),258 vars: map[string]string{"v1": "222"},259 host: "",260 path: "/111/222",261 shouldMatch: true,262 },263 {264 title: "PathPrefix route with pattern, URL prefix in request does not match",265 route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),266 request: newRequest("GET", "http://localhost/111/aaa/333"),267 vars: map[string]string{"v1": "222"},268 host: "",269 path: "/111/222",270 shouldMatch: false,271 },272 {273 title: "PathPrefix route with multiple patterns, match",274 route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),275 request: newRequest("GET", "http://localhost/111/222/333"),276 vars: map[string]string{"v1": "111", "v2": "222"},277 host: "",278 path: "/111/222",279 shouldMatch: true,280 },281 {282 title: "PathPrefix route with multiple patterns, URL prefix in request does not match",283 route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),284 request: newRequest("GET", "http://localhost/111/aaa/333"),285 vars: map[string]string{"v1": "111", "v2": "222"},286 host: "",287 path: "/111/222",288 shouldMatch: false,289 },290 }291 for _, test := range tests {292 testRoute(t, test)293 }294}295func TestHostPath(t *testing.T) {296 tests := []routeTest{297 {298 title: "Host and Path route, match",299 route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),300 request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),301 vars: map[string]string{},302 host: "",303 path: "",304 shouldMatch: true,305 },306 {307 title: "Host and Path route, wrong host in request URL",308 route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),309 request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),310 vars: map[string]string{},311 host: "",312 path: "",313 shouldMatch: false,314 },315 {316 title: "Host and Path route with pattern, match",317 route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),318 request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),319 vars: map[string]string{"v1": "bbb", "v2": "222"},320 host: "aaa.bbb.ccc",321 path: "/111/222/333",322 shouldMatch: true,323 },324 {325 title: "Host and Path route with pattern, URL in request does not match",326 route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),327 request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),328 vars: map[string]string{"v1": "bbb", "v2": "222"},329 host: "aaa.bbb.ccc",330 path: "/111/222/333",331 shouldMatch: false,332 },333 {334 title: "Host and Path route with multiple patterns, match",335 route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),336 request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),337 vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},338 host: "aaa.bbb.ccc",339 path: "/111/222/333",340 shouldMatch: true,341 },342 {343 title: "Host and Path route with multiple patterns, URL in request does not match",344 route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),345 request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),346 vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},347 host: "aaa.bbb.ccc",348 path: "/111/222/333",349 shouldMatch: false,350 },351 }352 for _, test := range tests {353 testRoute(t, test)354 }355}356func TestHeaders(t *testing.T) {357 // newRequestHeaders creates a new request with a method, url, and headers358 newRequestHeaders := func(method, url string, headers map[string]string) *http.Request {359 req, err := http.NewRequest(method, url, nil)360 if err != nil {361 panic(err)362 }363 for k, v := range headers {364 req.Header.Add(k, v)365 }366 return req367 }368 tests := []routeTest{369 {370 title: "Headers route, match",371 route: new(Route).Headers("foo", "bar", "baz", "ding"),372 request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}),373 vars: map[string]string{},374 host: "",375 path: "",376 shouldMatch: true,377 },378 {379 title: "Headers route, bad header values",380 route: new(Route).Headers("foo", "bar", "baz", "ding"),381 request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}),382 vars: map[string]string{},383 host: "",384 path: "",385 shouldMatch: false,386 },387 }388 for _, test := range tests {389 testRoute(t, test)390 }391}392func TestMethods(t *testing.T) {393 tests := []routeTest{394 {395 title: "Methods route, match GET",396 route: new(Route).Methods("GET", "POST"),397 request: newRequest("GET", "http://localhost"),398 vars: map[string]string{},399 host: "",400 path: "",401 shouldMatch: true,402 },403 {404 title: "Methods route, match POST",405 route: new(Route).Methods("GET", "POST"),406 request: newRequest("POST", "http://localhost"),407 vars: map[string]string{},408 host: "",409 path: "",410 shouldMatch: true,411 },412 {413 title: "Methods route, bad method",414 route: new(Route).Methods("GET", "POST"),415 request: newRequest("PUT", "http://localhost"),416 vars: map[string]string{},417 host: "",418 path: "",419 shouldMatch: false,420 },421 }422 for _, test := range tests {423 testRoute(t, test)424 }425}426func TestQueries(t *testing.T) {427 tests := []routeTest{428 {429 title: "Queries route, match",430 route: new(Route).Queries("foo", "bar", "baz", "ding"),431 request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),432 vars: map[string]string{},433 host: "",434 path: "",435 shouldMatch: true,436 },437 {438 title: "Queries route, match with a query string",439 route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),440 request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"),441 vars: map[string]string{},442 host: "",443 path: "",444 shouldMatch: true,445 },446 {447 title: "Queries route, bad query",448 route: new(Route).Queries("foo", "bar", "baz", "ding"),449 request: newRequest("GET", "http://localhost?foo=bar&baz=dong"),450 vars: map[string]string{},451 host: "",452 path: "",453 shouldMatch: false,454 },455 }456 for _, test := range tests {457 testRoute(t, test)458 }459}460func TestSchemes(t *testing.T) {461 tests := []routeTest{462 // Schemes463 {464 title: "Schemes route, match https",465 route: new(Route).Schemes("https", "ftp"),466 request: newRequest("GET", "https://localhost"),467 vars: map[string]string{},468 host: "",469 path: "",470 shouldMatch: true,471 },472 {473 title: "Schemes route, match ftp",474 route: new(Route).Schemes("https", "ftp"),475 request: newRequest("GET", "ftp://localhost"),476 vars: map[string]string{},477 host: "",478 path: "",479 shouldMatch: true,480 },481 {482 title: "Schemes route, bad scheme",483 route: new(Route).Schemes("https", "ftp"),484 request: newRequest("GET", "http://localhost"),485 vars: map[string]string{},486 host: "",487 path: "",488 shouldMatch: false,489 },490 }491 for _, test := range tests {492 testRoute(t, test)493 }494}495func TestMatcherFunc(t *testing.T) {496 m := func(r *http.Request, m *RouteMatch) bool {497 if r.URL.Host == "aaa.bbb.ccc" {498 return true499 }500 return false501 }502 tests := []routeTest{503 {504 title: "MatchFunc route, match",505 route: new(Route).MatcherFunc(m),506 request: newRequest("GET", "http://aaa.bbb.ccc"),507 vars: map[string]string{},508 host: "",509 path: "",510 shouldMatch: true,511 },512 {513 title: "MatchFunc route, non-match",514 route: new(Route).MatcherFunc(m),515 request: newRequest("GET", "http://aaa.222.ccc"),516 vars: map[string]string{},517 host: "",518 path: "",519 shouldMatch: false,520 },521 }522 for _, test := range tests {523 testRoute(t, test)524 }525}526func TestSubRouter(t *testing.T) {527 subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter()528 subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter()529 tests := []routeTest{530 {531 route: subrouter1.Path("/{v2:[a-z]+}"),532 request: newRequest("GET", "http://aaa.google.com/bbb"),533 vars: map[string]string{"v1": "aaa", "v2": "bbb"},534 host: "aaa.google.com",535 path: "/bbb",536 shouldMatch: true,537 },538 {539 route: subrouter1.Path("/{v2:[a-z]+}"),540 request: newRequest("GET", "http://111.google.com/111"),541 vars: map[string]string{"v1": "aaa", "v2": "bbb"},542 host: "aaa.google.com",543 path: "/bbb",544 shouldMatch: false,545 },546 {547 route: subrouter2.Path("/baz/{v2}"),548 request: newRequest("GET", "http://localhost/foo/bar/baz/ding"),549 vars: map[string]string{"v1": "bar", "v2": "ding"},550 host: "",551 path: "/foo/bar/baz/ding",552 shouldMatch: true,553 },554 {555 route: subrouter2.Path("/baz/{v2}"),556 request: newRequest("GET", "http://localhost/foo/bar"),557 vars: map[string]string{"v1": "bar", "v2": "ding"},558 host: "",559 path: "/foo/bar/baz/ding",560 shouldMatch: false,561 },562 }563 for _, test := range tests {564 testRoute(t, test)565 }566}567func TestNamedRoutes(t *testing.T) {568 r1 := NewRouter()569 r1.NewRoute().Name("a")570 r1.NewRoute().Name("b")571 r1.NewRoute().Name("c")572 r2 := r1.NewRoute().Subrouter()573 r2.NewRoute().Name("d")574 r2.NewRoute().Name("e")575 r2.NewRoute().Name("f")576 r3 := r2.NewRoute().Subrouter()577 r3.NewRoute().Name("g")578 r3.NewRoute().Name("h")579 r3.NewRoute().Name("i")580 if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 {581 t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes)582 } else if r1.Get("i") == nil {583 t.Errorf("Subroute name not registered")584 }585}586func TestStrictSlash(t *testing.T) {587 r := NewRouter()588 r.StrictSlash(true)589 tests := []routeTest{590 {591 title: "Redirect path without slash",592 route: r.NewRoute().Path("/111/"),593 request: newRequest("GET", "http://localhost/111"),594 vars: map[string]string{},595 host: "",596 path: "/111/",597 shouldMatch: true,598 shouldRedirect: true,599 },600 {601 title: "Do not redirect path with slash",602 route: r.NewRoute().Path("/111/"),603 request: newRequest("GET", "http://localhost/111/"),604 vars: map[string]string{},605 host: "",606 path: "/111/",607 shouldMatch: true,608 shouldRedirect: false,609 },610 {611 title: "Redirect path with slash",612 route: r.NewRoute().Path("/111"),613 request: newRequest("GET", "http://localhost/111/"),614 vars: map[string]string{},615 host: "",616 path: "/111",617 shouldMatch: true,618 shouldRedirect: true,619 },620 {621 title: "Do not redirect path without slash",622 route: r.NewRoute().Path("/111"),623 request: newRequest("GET", "http://localhost/111"),624 vars: map[string]string{},625 host: "",626 path: "/111",627 shouldMatch: true,628 shouldRedirect: false,629 },630 {631 title: "Propagate StrictSlash to subrouters",632 route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"),633 request: newRequest("GET", "http://localhost/static/images"),634 vars: map[string]string{},635 host: "",636 path: "/static/images/",637 shouldMatch: true,638 shouldRedirect: true,639 },640 {641 title: "Ignore StrictSlash for path prefix",642 route: r.NewRoute().PathPrefix("/static/"),643 request: newRequest("GET", "http://localhost/static/logo.png"),644 vars: map[string]string{},645 host: "",646 path: "/static/",647 shouldMatch: true,648 shouldRedirect: false,649 },650 }651 for _, test := range tests {652 testRoute(t, test)653 }654}655// ----------------------------------------------------------------------------656// Helpers657// ----------------------------------------------------------------------------658func getRouteTemplate(route *Route) string {659 host, path := "none", "none"660 if route.regexp != nil {661 if route.regexp.host != nil {662 host = route.regexp.host.template663 }664 if route.regexp.path != nil {665 path = route.regexp.path.template666 }667 }668 return fmt.Sprintf("Host: %v, Path: %v", host, path)669}670func testRoute(t *testing.T, test routeTest) {671 request := test.request672 route := test.route673 vars := test.vars674 shouldMatch := test.shouldMatch675 host := test.host676 path := test.path677 url := test.host + test.path678 shouldRedirect := test.shouldRedirect679 var match RouteMatch680 ok := route.Match(request, &match)681 if ok != shouldMatch {682 msg := "Should match"683 if !shouldMatch {684 msg = "Should not match"685 }686 t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars)687 return688 }689 if shouldMatch {690 if test.vars != nil && !stringMapEqual(test.vars, match.Vars) {691 t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars)692 return693 }694 if host != "" {695 u, _ := test.route.URLHost(mapToPairs(match.Vars)...)696 if host != u.Host {697 t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route))698 return699 }700 }701 if path != "" {702 u, _ := route.URLPath(mapToPairs(match.Vars)...)703 if path != u.Path {704 t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route))705 return706 }707 }708 if url != "" {709 u, _ := route.URL(mapToPairs(match.Vars)...)710 if url != u.Host+u.Path {711 t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route))712 return713 }714 }715 if shouldRedirect && match.Handler == nil {716 t.Errorf("(%v) Did not redirect", test.title)717 return718 }719 if !shouldRedirect && match.Handler != nil {720 t.Errorf("(%v) Unexpected redirect", test.title)721 return722 }723 }724}725// Tests that the context is cleared or not cleared properly depending on726// the configuration of the router727func TestKeepContext(t *testing.T) {728 func1 := func(w http.ResponseWriter, r *http.Request) {}729 r := NewRouter()730 r.HandleFunc("/", func1).Name("func1")731 req, _ := http.NewRequest("GET", "http://localhost/", nil)732 context.Set(req, "t", 1)733 res := new(http.ResponseWriter)734 r.ServeHTTP(*res, req)735 if _, ok := context.GetOk(req, "t"); ok {736 t.Error("Context should have been cleared at end of request")737 }738 r.KeepContext = true739 req, _ = http.NewRequest("GET", "http://localhost/", nil)740 context.Set(req, "t", 1)741 r.ServeHTTP(*res, req)742 if _, ok := context.GetOk(req, "t"); !ok {743 t.Error("Context should NOT have been cleared at end of request")744 }745}746type TestA301ResponseWriter struct {747 hh http.Header748 status int749}750func (ho TestA301ResponseWriter) Header() http.Header {751 return http.Header(ho.hh)752}753func (ho TestA301ResponseWriter) Write(b []byte) (int, error) {754 return 0, nil755}756func (ho TestA301ResponseWriter) WriteHeader(code int) {757 ho.status = code758}759func Test301Redirect(t *testing.T) {760 m := make(http.Header)761 func1 := func(w http.ResponseWriter, r *http.Request) {}762 func2 := func(w http.ResponseWriter, r *http.Request) {}763 r := NewRouter()764 r.HandleFunc("/api/", func2).Name("func2")765 r.HandleFunc("/", func1).Name("func1")766 req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil)767 res := TestA301ResponseWriter{768 hh: m,769 status: 0,770 }771 r.ServeHTTP(&res, req)772 if "http://localhost/api/?abc=def" != res.hh["Location"][0] {773 t.Errorf("Should have complete URL with query string")774 }775}776// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW777func TestSubrouterHeader(t *testing.T) {778 expected := "func1 response"779 func1 := func(w http.ResponseWriter, r *http.Request) {780 fmt.Fprint(w, expected)781 }782 func2 := func(http.ResponseWriter, *http.Request) {}783 r := NewRouter()784 s := r.Headers("SomeSpecialHeader", "").Subrouter()785 s.HandleFunc("/", func1).Name("func1")786 r.HandleFunc("/", func2).Name("func2")787 req, _ := http.NewRequest("GET", "http://localhost/", nil)788 req.Header.Add("SomeSpecialHeader", "foo")789 match := new(RouteMatch)790 matched := r.Match(req, match)791 if !matched {792 t.Errorf("Should match request")793 }794 if match.Route.GetName() != "func1" {795 t.Errorf("Expecting func1 handler, got %s", match.Route.GetName())796 }797 resp := NewRecorder()798 match.Handler.ServeHTTP(resp, req)799 if resp.Body.String() != expected {800 t.Errorf("Expecting %q", expected)801 }802}803// mapToPairs converts a string map to a slice of string pairs804func mapToPairs(m map[string]string) []string {805 var i int806 p := make([]string, len(m)*2)807 for k, v := range m {808 p[i] = k809 p[i+1] = v810 i += 2811 }812 return p...

Full Screen

Full Screen

old_test.go

Source:old_test.go Github

copy

Full Screen

...69 Methods("POST").70 Schemes("http").71 Headers("Content-Type", "application/json")72 reset := func() {73 // Everything match.74 scheme = "https"75 host = "www.google.com"76 path = "/product/42"77 query = "?foo=bar"78 method = "GET"79 headers = map[string]string{"X-Requested-With": "XMLHttpRequest"}80 resultVars = map[bool]map[string]string{81 true: {"var1": "www", "var2": "product", "var3": "42"},82 false: {},83 }84 }85 reset2 := func() {86 // Everything match.87 scheme = "http"88 host = "www.google.com"89 path = "/foo/product/42/path/that/is/ignored"90 query = "?baz=ding"91 method = "POST"92 headers = map[string]string{"Content-Type": "application/json"}93 resultVars = map[bool]map[string]string{94 true: {"var4": "google", "var5": "product", "var6": "42"},95 false: {},96 }97 }98 match := func(shouldMatch bool) {99 url := scheme + "://" + host + path + query100 request, _ := http.NewRequest(method, url, nil)101 for key, value := range headers {102 request.Header.Add(key, value)103 }104 var routeMatch RouteMatch105 matched := router.Match(request, &routeMatch)106 if matched != shouldMatch {107 t.Errorf("Expected: %v\nGot: %v\nRequest: %v %v", shouldMatch, matched, request.Method, url)108 }109 if matched {110 currentRoute := routeMatch.Route111 if currentRoute == nil {112 t.Errorf("Expected a current route.")113 }114 vars := routeMatch.Vars115 expectedVars := resultVars[shouldMatch]116 if len(vars) != len(expectedVars) {117 t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars)118 }119 for name, value := range vars {120 if expectedVars[name] != value {121 t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars)122 }123 }124 }125 }126 // 1st route --------------------------------------------------------------127 // Everything match.128 reset()129 match(true)130 // Scheme doesn't match.131 reset()132 scheme = "http"133 match(false)134 // Host doesn't match.135 reset()136 host = "www.mygoogle.com"137 match(false)138 // Path doesn't match.139 reset()140 path = "/product/notdigits"141 match(false)142 // Query doesn't match.143 reset()144 query = "?foo=baz"145 match(false)146 // Method doesn't match.147 reset()148 method = "POST"149 match(false)150 // Header doesn't match.151 reset()152 headers = map[string]string{}153 match(false)154 // Everything match, again.155 reset()156 match(true)157 // 2nd route --------------------------------------------------------------158 // Everything match.159 reset2()160 match(true)161 // Scheme doesn't match.162 reset2()163 scheme = "https"164 match(false)165 // Host doesn't match.166 reset2()167 host = "sub.google.com"168 match(false)169 // Path doesn't match.170 reset2()171 path = "/bar/product/42"172 match(false)173 // Query doesn't match.174 reset2()175 query = "?foo=baz"176 match(false)177 // Method doesn't match.178 reset2()179 method = "GET"180 match(false)181 // Header doesn't match.182 reset2()183 headers = map[string]string{}184 match(false)185 // Everything match, again.186 reset2()187 match(true)188}189type headerMatcherTest struct {190 matcher headerMatcher191 headers map[string]string192 result bool193}194var headerMatcherTests = []headerMatcherTest{195 {196 matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}),197 headers: map[string]string{"X-Requested-With": "XMLHttpRequest"},198 result: true,199 },200 {201 matcher: headerMatcher(map[string]string{"x-requested-with": ""}),202 headers: map[string]string{"X-Requested-With": "anything"},203 result: true,204 },205 {206 matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}),207 headers: map[string]string{},208 result: false,209 },210}211type hostMatcherTest struct {212 matcher *Route213 url string214 vars map[string]string215 result bool216}217var hostMatcherTests = []hostMatcherTest{218 {219 matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"),220 url: "http://abc.def.ghi/",221 vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"},222 result: true,223 },224 {225 matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"),226 url: "http://a.b.c/",227 vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"},228 result: false,229 },230}231type methodMatcherTest struct {232 matcher methodMatcher233 method string234 result bool235}236var methodMatcherTests = []methodMatcherTest{237 {238 matcher: methodMatcher([]string{"GET", "POST", "PUT"}),239 method: "GET",240 result: true,241 },242 {243 matcher: methodMatcher([]string{"GET", "POST", "PUT"}),244 method: "POST",245 result: true,246 },247 {248 matcher: methodMatcher([]string{"GET", "POST", "PUT"}),249 method: "PUT",250 result: true,251 },252 {253 matcher: methodMatcher([]string{"GET", "POST", "PUT"}),254 method: "DELETE",255 result: false,256 },257}258type pathMatcherTest struct {259 matcher *Route260 url string261 vars map[string]string262 result bool263}264var pathMatcherTests = []pathMatcherTest{265 {266 matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"),267 url: "http://localhost:8080/123/456/789",268 vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"},269 result: true,270 },271 {272 matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"),273 url: "http://localhost:8080/1/2/3",274 vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"},275 result: false,276 },277}278type schemeMatcherTest struct {279 matcher schemeMatcher280 url string281 result bool282}283var schemeMatcherTests = []schemeMatcherTest{284 {285 matcher: schemeMatcher([]string{"http", "https"}),286 url: "http://localhost:8080/",287 result: true,288 },289 {290 matcher: schemeMatcher([]string{"http", "https"}),291 url: "https://localhost:8080/",292 result: true,293 },294 {295 matcher: schemeMatcher([]string{"https"}),296 url: "http://localhost:8080/",297 result: false,298 },299 {300 matcher: schemeMatcher([]string{"http"}),301 url: "https://localhost:8080/",302 result: false,303 },304}305type urlBuildingTest struct {306 route *Route307 vars []string308 url string309}310var urlBuildingTests = []urlBuildingTest{311 {312 route: new(Route).Host("foo.domain.com"),313 vars: []string{},314 url: "http://foo.domain.com",315 },316 {317 route: new(Route).Host("{subdomain}.domain.com"),318 vars: []string{"subdomain", "bar"},319 url: "http://bar.domain.com",320 },321 {322 route: new(Route).Host("foo.domain.com").Path("/articles"),323 vars: []string{},324 url: "http://foo.domain.com/articles",325 },326 {327 route: new(Route).Path("/articles"),328 vars: []string{},329 url: "/articles",330 },331 {332 route: new(Route).Path("/articles/{category}/{id:[0-9]+}"),333 vars: []string{"category", "technology", "id", "42"},334 url: "/articles/technology/42",335 },336 {337 route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"),338 vars: []string{"subdomain", "foo", "category", "technology", "id", "42"},339 url: "http://foo.domain.com/articles/technology/42",340 },341 {342 route: new(Route).Host("example.com").Schemes("https", "http"),343 vars: []string{},344 url: "https://example.com",345 },346}347func TestHeaderMatcher(t *testing.T) {348 for _, v := range headerMatcherTests {349 request, _ := http.NewRequest("GET", "http://localhost:8080/", nil)350 for key, value := range v.headers {351 request.Header.Add(key, value)352 }353 var routeMatch RouteMatch354 result := v.matcher.Match(request, &routeMatch)355 if result != v.result {356 if v.result {357 t.Errorf("%#v: should match %v.", v.matcher, request.Header)358 } else {359 t.Errorf("%#v: should not match %v.", v.matcher, request.Header)360 }361 }362 }363}364func TestHostMatcher(t *testing.T) {365 for _, v := range hostMatcherTests {366 request, _ := http.NewRequest("GET", v.url, nil)367 var routeMatch RouteMatch368 result := v.matcher.Match(request, &routeMatch)369 vars := routeMatch.Vars370 if result != v.result {371 if v.result {372 t.Errorf("%#v: should match %v.", v.matcher, v.url)373 } else {374 t.Errorf("%#v: should not match %v.", v.matcher, v.url)375 }376 }377 if result {378 if len(vars) != len(v.vars) {379 t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars))380 }381 for name, value := range vars {382 if v.vars[name] != value {383 t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value)384 }385 }386 } else {387 if len(vars) != 0 {388 t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars))389 }390 }391 }392}393func TestMethodMatcher(t *testing.T) {394 for _, v := range methodMatcherTests {395 request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil)396 var routeMatch RouteMatch397 result := v.matcher.Match(request, &routeMatch)398 if result != v.result {399 if v.result {400 t.Errorf("%#v: should match %v.", v.matcher, v.method)401 } else {402 t.Errorf("%#v: should not match %v.", v.matcher, v.method)403 }404 }405 }406}407func TestPathMatcher(t *testing.T) {408 for _, v := range pathMatcherTests {409 request, _ := http.NewRequest("GET", v.url, nil)410 var routeMatch RouteMatch411 result := v.matcher.Match(request, &routeMatch)412 vars := routeMatch.Vars413 if result != v.result {414 if v.result {415 t.Errorf("%#v: should match %v.", v.matcher, v.url)416 } else {417 t.Errorf("%#v: should not match %v.", v.matcher, v.url)418 }419 }420 if result {421 if len(vars) != len(v.vars) {422 t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars))423 }424 for name, value := range vars {425 if v.vars[name] != value {426 t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value)427 }428 }429 } else {430 if len(vars) != 0 {431 t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars))432 }433 }434 }435}436func TestSchemeMatcher(t *testing.T) {437 for _, v := range schemeMatcherTests {438 request, _ := http.NewRequest("GET", v.url, nil)439 var routeMatch RouteMatch440 result := v.matcher.Match(request, &routeMatch)441 if result != v.result {442 if v.result {443 t.Errorf("%#v: should match %v.", v.matcher, v.url)444 } else {445 t.Errorf("%#v: should not match %v.", v.matcher, v.url)446 }447 }448 }449}450func TestUrlBuilding(t *testing.T) {451 for _, v := range urlBuildingTests {452 u, _ := v.route.URL(v.vars...)453 url := u.String()454 if url != v.url {455 t.Errorf("expected %v, got %v", v.url, url)456 }457 }458 ArticleHandler := func(w http.ResponseWriter, r *http.Request) {459 }460 router := NewRouter()461 router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article")462 url, _ := router.Get("article").URL("category", "technology", "id", "42")463 expected := "/articles/technology/42"464 if url.String() != expected {465 t.Errorf("Expected %v, got %v", expected, url.String())466 }467}468func TestMatchedRouteName(t *testing.T) {469 routeName := "stock"470 router := NewRouter()471 route := router.NewRoute().Path("/products/").Name(routeName)472 url := "http://www.example.com/products/"473 request, _ := http.NewRequest("GET", url, nil)474 var rv RouteMatch475 ok := router.Match(request, &rv)476 if !ok || rv.Route != route {477 t.Errorf("Expected same route, got %+v.", rv.Route)478 }479 retName := rv.Route.GetName()480 if retName != routeName {481 t.Errorf("Expected %q, got %q.", routeName, retName)482 }483}484func TestSubRouting(t *testing.T) {485 // Example from docs.486 router := NewRouter()487 subrouter := router.NewRoute().Host("www.example.com").Subrouter()488 route := subrouter.NewRoute().Path("/products/").Name("products")489 url := "http://www.example.com/products/"490 request, _ := http.NewRequest("GET", url, nil)491 var rv RouteMatch492 ok := router.Match(request, &rv)493 if !ok || rv.Route != route {494 t.Errorf("Expected same route, got %+v.", rv.Route)495 }496 u, _ := router.Get("products").URL()497 builtURL := u.String()498 // Yay, subroute aware of the domain when building!499 if builtURL != url {500 t.Errorf("Expected %q, got %q.", url, builtURL)501 }502}503func TestVariableNames(t *testing.T) {504 route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}")505 if route.err == nil {506 t.Errorf("Expected error for duplicated variable names")507 }508}509func TestRedirectSlash(t *testing.T) {510 var route *Route511 var routeMatch RouteMatch512 r := NewRouter()513 r.StrictSlash(false)514 route = r.NewRoute()515 if route.strictSlash != false {516 t.Errorf("Expected false redirectSlash.")517 }518 r.StrictSlash(true)519 route = r.NewRoute()520 if route.strictSlash != true {521 t.Errorf("Expected true redirectSlash.")522 }523 route = new(Route)524 route.strictSlash = true525 route.Path("/{arg1}/{arg2:[0-9]+}/")526 request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil)527 routeMatch = RouteMatch{}528 _ = route.Match(request, &routeMatch)529 vars := routeMatch.Vars530 if vars["arg1"] != "foo" {531 t.Errorf("Expected foo.")532 }533 if vars["arg2"] != "123" {534 t.Errorf("Expected 123.")535 }536 rsp := NewRecorder()537 routeMatch.Handler.ServeHTTP(rsp, request)538 if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" {539 t.Errorf("Expected redirect header.")540 }541 route = new(Route)542 route.strictSlash = true543 route.Path("/{arg1}/{arg2:[0-9]+}")544 request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil)545 routeMatch = RouteMatch{}546 _ = route.Match(request, &routeMatch)547 vars = routeMatch.Vars548 if vars["arg1"] != "foo" {549 t.Errorf("Expected foo.")550 }551 if vars["arg2"] != "123" {552 t.Errorf("Expected 123.")553 }554 rsp = NewRecorder()555 routeMatch.Handler.ServeHTTP(rsp, request)556 if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" {557 t.Errorf("Expected redirect header.")558 }559}560// Test for the new regexp library, still not available in stable Go.561func TestNewRegexp(t *testing.T) {562 var p *routeRegexp563 var matches []string564 tests := map[string]map[string][]string{565 "/{foo:a{2}}": {566 "/a": nil,567 "/aa": {"aa"},568 "/aaa": nil,569 "/aaaa": nil,570 },571 "/{foo:a{2,}}": {572 "/a": nil,573 "/aa": {"aa"},574 "/aaa": {"aaa"},575 "/aaaa": {"aaaa"},576 },577 "/{foo:a{2,3}}": {578 "/a": nil,579 "/aa": {"aa"},580 "/aaa": {"aaa"},581 "/aaaa": nil,582 },583 "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": {584 "/a": nil,585 "/ab": nil,586 "/abc": nil,587 "/abcd": nil,588 "/abc/ab": {"abc", "ab"},589 "/abc/abc": nil,590 "/abcd/ab": nil,591 },592 `/{foo:\w{3,}}/{bar:\d{2,}}`: {593 "/a": nil,594 "/ab": nil,595 "/abc": nil,596 "/abc/1": nil,597 "/abc/12": {"abc", "12"},598 "/abcd/12": {"abcd", "12"},599 "/abcd/123": {"abcd", "123"},600 },601 }602 for pattern, paths := range tests {603 p, _ = newRouteRegexp(pattern, regexpTypePath, routeRegexpOptions{})604 for path, result := range paths {605 matches = p.regexp.FindStringSubmatch(path)606 if result == nil {607 if matches != nil {608 t.Errorf("%v should not match %v.", pattern, path)609 }610 } else {611 if len(matches) != len(result)+1 {612 t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches))613 } else {614 for k, v := range result {615 if matches[k+1] != v {616 t.Errorf("Expected %v, got %v.", v, matches[k+1])617 }618 }619 }620 }621 }622 }623}...

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r := http.NewServeMux()4 r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {5 fmt.Fprintf(w, "Hello, %q", http.PathEscape(r.URL.Path))6 })7 http.ListenAndServe(":8080", r)8}

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprintf(w, "Hello, %q", r.URL.Path)5 })6 http.ListenAndServe(":8080", nil)7}8import (9func main() {10 http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {11 fmt.Fprintf(w, "Hello, %q", r.URL.Path)12 })13 http.ListenAndServe(":8080", nil)14}15import (16func main() {17 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {18 fmt.Fprintf(w, "Bye, %q", r.URL.Path)19 })20 http.ListenAndServe(":8080", nil)21}22import (23func main() {24 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {25 fmt.Fprintf(w, "Bye, %q", r.URL.Path)26 })27 http.ListenAndServe(":8080", nil)28}29import (30func main() {31 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {32 fmt.Fprintf(w, "Bye, %q", r.URL.Path)33 })34 http.ListenAndServe(":8080", nil)35}36import (37func main() {38 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {39 fmt.Fprintf(w, "Bye, %q", r.URL.Path)40 })41 http.ListenAndServe(":8080", nil)42}43import (44func main() {45 http.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error:", err)5 }6 fmt.Println(r)7 fmt.Println(r.URL)8 fmt.Println(r.URL.Host)9 fmt.Println(r.URL.Scheme)10 fmt.Println(r.URL.Path)11 fmt.Println(r.URL.RawQuery)12 fmt.Println(r.URL.Fragment)13}14import (15func main() {16 if err != nil {17 fmt.Println("Error:", err)18 }19 fmt.Println(r)20 fmt.Println(r.URL)21 fmt.Println(r.URL.Host)22 fmt.Println(r.URL.Scheme)23 fmt.Println(r.URL.Path)24 fmt.Println(r.URL.RawQuery)25 fmt.Println(r.URL.Fragment)26}27import (28func main() {29 if err != nil {30 fmt.Println("Error:", err)31 }32 fmt.Println(r)33 fmt.Println(r.URL)34 fmt.Println(r.URL.Host)35 fmt.Println(r.URL.Scheme)36 fmt.Println(r.URL.Path)37 fmt.Println(r.URL.RawQuery)38 fmt.Println(r.URL.Fragment)39}

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Start")4 http.HandleFunc("/", handler)5 http.ListenAndServe(":8080", nil)6}7func handler(w http.ResponseWriter, r *http.Request) {8 fmt.Println("handler called")9 fmt.Println(r.URL.Path)10 if r.URL.Path == "/home" {11 fmt.Println("Home Page")12 } else if r.URL.Path == "/about" {13 fmt.Println("About Page")14 } else {15 fmt.Println("Page Not Found")16 }17}18import (19func main() {20 fmt.Println("Start")21 http.HandleFunc("/", handler)22 http.ListenAndServe(":8080", nil)23}24func handler(w http.ResponseWriter, r *http.Request) {25 fmt.Println("handler called")26 fmt.Println(r.URL.Path)27 if r.URL.Path == "/" {28 fmt.Println("Home Page")29 } else if r.URL.Path == "/about" {30 fmt.Println("About Page")31 } else {32 fmt.Println("Page Not Found")33 }34}35import (36func main() {37 fmt.Println("Start")38 http.HandleFunc("/", handler)39 http.ListenAndServe(":8080", nil)40}41func handler(w http.ResponseWriter, r *http.Request) {42 fmt.Println("handler called")43 fmt.Println(r.URL.Path)44 if r.URL.Path == "/" {45 fmt.Println("Home Page")46 } else if r.URL.Path == "/about" {47 fmt.Println("About Page")48 } else {49 fmt.Println("Page Not Found")50 }51}52import (53func main() {54 fmt.Println("Start")55 http.HandleFunc("/", handler)56 http.ListenAndServe(":8080", nil)57}58func handler(w http.ResponseWriter, r *http.Request) {59 fmt.Println("handler called")60 fmt.Println(r.URL.Path)61 if r.URL.Path == "/" {62 fmt.Println("Home Page")63 } else if r.URL.Path == "/about" {64 fmt.Println("About Page")65 } else {66 fmt.Println("Page Not Found")67 }68}

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Match method of http class")4 fmt.Println(http.Match("text/*", []string{"text/html"}))5 fmt.Println(http.Match("text/*", []string{"image/gif"}))6 fmt.Println(http.Match("text/*;q=0.3,image/*;q=0.7", []string{"image/gif"}))7 fmt.Println(http.Match("text/*;q=0.3,image/*;q=0.7", []string{"text/html"}))8 fmt.Println(http.Match("text/*;q=0.3,image/*;q=0.7", []string{"image/png"}))9}

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Valid URL")4 } else {5 fmt.Println("Invalid URL")6 }7}8import (9func main() {10 fmt.Println("Valid URL")11 } else {12 fmt.Println("Invalid URL")13 }14}15import (16func main() {17 fmt.Println("Valid URL")18 } else {19 fmt.Println("Invalid URL")20 }21}22import (23func main() {24 fmt.Println("Valid URL")25 } else {26 fmt.Println("Invalid URL")27 }28}29import (30func main() {31 fmt.Println("Valid URL")32 } else {33 fmt.Println("Invalid URL")34 }35}36import (37func main() {38 fmt.Println("Valid URL")39 } else {40 fmt.Println("Invalid URL")

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Print("Enter a url: ")4 fmt.Scan(&url)5 if pattern.MatchString(url) {6 matches := pattern.FindStringSubmatch(url)7 fmt.Println("The domain name is " + matches[1])8 } else {9 fmt.Println("Invalid url")10 }11}12func main() {13 fmt.Print("Enter a url: ")14 fmt.Scan(&url)15 if pattern.MatchString(url) {16 matches := pattern.FindStringSubmatch(url)17 fmt.Println("The domain name is " + matches[1])18 } else {19 fmt.Println("Invalid url")20 }21}22import (23func main() {24 fmt.Print("Enter a url: ")25 fmt.Scan(&url)26 if pattern.MatchString(url) {27 matches := pattern.FindStringSubmatch(url)28 fmt.Println("The domain name is " + matches[1])29 } else {30 fmt.Println("Invalid url")31 }32}33import (34func main() {35 fmt.Print("Enter a url: ")

Full Screen

Full Screen

match

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r := "/article/{id}"4 req, _ := http.NewRequest("GET", "/article/123", nil)5 m := http.NewServeMux()6 m.HandleFunc(r, func(w http.ResponseWriter, r *http.Request) {7 id := r.Context().Value("id")8 fmt.Fprintf(w, "ID: %s", id)9 })10 m.ServeHTTP(nil, req)11}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful