How to use Route method of got Package

Best Got code snippet using got.Route

routes_test.go

Source:routes_test.go Github

copy

Full Screen

...9	"netstack/routes"10	"netstack/util"11	"github.com/google/netstack/tcpip"12)13var testRouteTable = []routes.ExtendedRoute{14	// nic, subnet, gateway, metric, tracksInterface, dynamic, enabled15	createExtendedRoute(1, "127.0.0.1/32", "", 100, true, false, true),                 // loopback16	createExtendedRoute(4, "192.168.1.0/24", "", 100, true, true, true),                // DHCP IP (eth)17	createExtendedRoute(2, "192.168.100.0/24", "", 200, true, true, true),              // DHCP IP (wlan)18	createExtendedRoute(3, "10.1.2.0/23", "", 100, true, false, true),                  // static IP19	createExtendedRoute(2, "110.34.0.0/16", "192.168.100.10", 500, false, false, true), // static route20	createExtendedRoute(1, "::1/128", "", 100, true, false, true),                      // loopback21	// static route (eth)22	createExtendedRoute(4, "2610:1:22:123:34:faed::/96", "fe80::250:a8ff:9:79", 100, false, false, true),23	createExtendedRoute(4, "2622:0:2200:10::/64", "", 100, true, true, true),           // RA (eth)24	createExtendedRoute(4, "0.0.0.0/0", "192.168.1.1", 100, true, true, true),          // default (eth)25	createExtendedRoute(2, "0.0.0.0/0", "192.168.100.10", 200, true, true, true),       // default (wlan)26	createExtendedRoute(4, "::/0", "fe80::210:6e00:fe11:3265", 100, true, false, true), // default (eth)27}28func createRoute(nicid tcpip.NICID, subnet string, gateway string) tcpip.Route {29	_, s, _ := net.ParseCIDR(subnet)30	return tcpip.Route{31		Destination: tcpip.Address(s.IP),32		Mask:        tcpip.AddressMask(s.Mask),33		Gateway:     ipStringToAddress(gateway),34		NIC:         nicid,35	}36}37func createExtendedRoute(nicid tcpip.NICID, subnet string, gateway string, metric routes.Metric, tracksInterface bool, dynamic bool, enabled bool) routes.ExtendedRoute {38	return routes.ExtendedRoute{39		Route:                 createRoute(nicid, subnet, gateway),40		Metric:                metric,41		MetricTracksInterface: tracksInterface,42		Dynamic:               dynamic,43		Enabled:               enabled,44	}45}46func ipStringToAddress(ipStr string) tcpip.Address {47	return ipToAddress(net.ParseIP(ipStr))48}49func ipToAddress(ip net.IP) tcpip.Address {50	if v4 := ip.To4(); v4 != nil {51		return tcpip.Address(v4)52	}53	return tcpip.Address(ip)54}55func TestExtendedRouteMatch(t *testing.T) {56	for _, tc := range []struct {57		subnet string58		addr   string59		want   bool60	}{61		{"192.168.10.0/24", "192.168.10.0", true},62		{"192.168.10.0/24", "192.168.10.1", true},63		{"192.168.10.0/24", "192.168.10.10", true},64		{"192.168.10.0/24", "192.168.10.255", true},65		{"192.168.10.0/24", "192.168.11.1", false},66		{"192.168.10.0/24", "192.168.0.1", false},67		{"192.168.10.0/24", "192.167.10.1", false},68		{"192.168.10.0/24", "193.168.10.1", false},69		{"192.168.10.0/24", "0.0.0.0", false},70		{"123.220.0.0/14", "123.220.11.22", true},71		{"123.220.0.0/14", "123.221.11.22", true},72		{"123.220.0.0/14", "123.222.11.22", true},73		{"123.220.0.0/14", "123.223.11.22", true},74		{"123.220.0.0/14", "123.224.11.22", false},75		{"0.0.0.0/0", "0.0.0.0", true},76		{"0.0.0.0/0", "1.1.1.1", true},77		{"0.0.0.0/0", "255.255.255.255", true},78		{"2402:f000:5:8401::/64", "2402:f000:5:8401::", true},79		{"2402:f000:5:8401::/64", "2402:f000:5:8401::1", true},80		{"2402:f000:5:8401::/64", "2402:f000:5:8401:1:12:123::", true},81		{"2402:f000:5:8401::/64", "2402:f000:5:8402::", false},82		{"2402:f000:5:8401::/64", "2402:f000:15:8401::", false},83		{"2402:f000:5:8401::/64", "2402::5:8401::", false},84		{"2402:f000:5:8401::/64", "2400:f000:5:8401::", false},85		{"::/0", "::", true},86		{"::/0", "1:1:1:1:1:1:1:1", true},87		{"::/0", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", true},88	} {89		t.Run("RouteMatch", func(t *testing.T) {90			er := createExtendedRoute(1, tc.subnet, "", 100, true, true, true)91			addr := ipStringToAddress(tc.addr)92			if got := er.Match(addr); got != tc.want {93				t.Errorf("got match addr %v in subnet %v = %v, want = %v", tc.addr, tc.subnet, got, tc.want)94			}95		})96	}97}98func TestSortingLess(t *testing.T) {99	for _, tc := range []struct {100		subnet1 string101		metric1 routes.Metric102		nic1    tcpip.NICID103		subnet2 string104		metric2 routes.Metric105		nic2    tcpip.NICID106		want bool107	}{108		// non-default before default109		{"100.99.24.12/32", 100, 1, "0.0.0.0/0", 100, 1, true},110		{"10.144.0.0/12", 100, 1, "0.0.0.0/0", 100, 2, true},111		{"127.0.0.1/24", 100, 1, "0.0.0.0/0", 100, 1, true},112		{"2511:5f32:4:6:124::2:1/128", 100, 1, "::/0", 100, 1, true},113		{"fe80:ffff:0:1234:5:6::/96", 100, 2, "::/0", 100, 1, true},114		{"::1/128", 100, 2, "::/0", 100, 2, true},115		// IPv4 before IPv6116		{"100.99.24.12/32", 100, 1, "2511:5f32:4:6:124::2/120", 100, 1, true},117		{"100.99.24.12/32", 100, 2, "2605:32::12/128", 100, 1, true},118		{"127.0.0.1/24", 100, 1, "::1/128", 100, 1, true},119		{"0.0.0.0/0", 100, 1, "::/0", 100, 3, true},120		// longer prefix wins121		{"100.99.24.12/32", 100, 2, "100.99.24.12/31", 100, 1, true},122		{"100.99.24.12/32", 100, 1, "10.144.0.0/12", 100, 1, true},123		{"100.99.24.128/25", 100, 5, "127.0.0.1/24", 100, 3, true},124		{"2511:5f32:4:6:124::2:12/128", 100, 1, "2511:5f32:4:6:124::2:12/126", 100, 1, true},125		{"2511:5f32:4:6:124::2:12/128", 100, 1, "2605:32::12/127", 100, 1, true},126		{"fe80:ffff:0:1234:5:6::/96", 100, 2, "2511:5f32:4:6:124::/90", 100, 1, true},127		{"2511:5f32:4:6:124::2:1/128", 100, 1, "::1/120", 100, 2, true},128		// lower metric129		{"100.99.24.12/32", 100, 1, "10.1.21.31/32", 101, 1, true},130		{"100.99.24.12/32", 101, 1, "10.1.21.31/32", 100, 2, false},131		{"100.99.2.0/23", 100, 3, "10.1.22.0/23", 101, 1, true},132		{"100.99.2.0/23", 101, 1, "10.1.22.0/23", 100, 1, false},133		{"2511:5f32:4:6:124::2:1/128", 100, 1, "2605:32::12/128", 101, 1, true},134		{"2511:5f32:4:6:124::2:1/128", 101, 3, "2605:32::12/128", 100, 2, false},135		{"2511:5f32:4:6:124::2:1/96", 100, 1, "fe80:ffff:0:1234:5:6::/96", 101, 4, true},136		{"2511:5f32:4:6:124::2:1/96", 101, 1, "fe80:ffff:0:1234:5:6::/96", 100, 4, false},137		// tie-breaker: destination IPs138		{"10.1.21.31/32", 100, 2, "100.99.24.12/32", 100, 1, true},139		{"100.99.24.12/32", 100, 1, "10.1.21.31/32", 100, 3, false},140		{"2511:5f32:4:6:124::2:1/128", 100, 1, "2605:32::12/128", 100, 1, true},141		{"2605:32::12/128", 100, 1, "2511:5f32:4:6:124::2:1/128", 100, 1, false},142		// tie-breaker: NIC143		{"10.1.21.31/32", 100, 1, "10.1.21.31/32", 100, 2, true},144		{"10.1.21.31/32", 100, 2, "10.1.21.31/32", 100, 1, false},145		{"2511:5f32:4:6:124::2:1/128", 100, 1, "2511:5f32:4:6:124::2:1/128", 100, 2, true},146		{"2511:5f32:4:6:124::2:1/128", 100, 2, "2511:5f32:4:6:124::2:1/128", 100, 1, false},147	} {148		name := fmt.Sprintf("Test-%s@nic%v[m:%v]_<_%s@nic%v[m:%v]", tc.subnet1, tc.nic1, tc.metric1, tc.subnet2, tc.nic2, tc.metric2)149		t.Run(name, func(t *testing.T) {150			e1 := createExtendedRoute(tc.nic1, tc.subnet1, "", tc.metric1, true, true, true)151			e2 := createExtendedRoute(tc.nic2, tc.subnet2, "", tc.metric2, true, true, true)152			if got := routes.Less(&e1, &e2); got != tc.want {153				t.Errorf("got Less(%v, %v) = %v, want = %v", &e1, &e2, got, tc.want)154			}155			// reverse test156			reverseWant := !tc.want157			if got := routes.Less(&e2, &e1); got != reverseWant {158				t.Errorf("Less(%v, %v) = %v, want = %v", e2, e1, got, reverseWant)159			}160		})161	}162}163func changeByte(b []byte) []byte {164	b[0] = ^b[0]165	return b166}167func TestIsSameRoute(t *testing.T) {168	gatewaysWithPrefix := []string{"127.0.0.1/32", "0.0.0.0/0", "123.220.3.14/14", "192.168.10.1/24",169		"::1/128", "::/128", "2605:143:32:113::1/64", "fe80:4234:242f:1111:5:243:5:4f/88"}170	nics := []tcpip.NICID{1, 2}171	for _, nic1 := range nics {172		t.Run(fmt.Sprintf("nic1=%v", nic1), func(t *testing.T) {173			for _, gp1 := range gatewaysWithPrefix {174				t.Run(fmt.Sprintf("gp1=%v", gp1), func(t *testing.T) {175					ip, s, err := net.ParseCIDR(gp1)176					if err != nil {177						t.Fatalf("net.ParseCIDR(%v) failed", gp1)178					}179					route1 := tcpip.Route{180						Destination: tcpip.Address(ipToAddress(s.IP)),181						Mask:        tcpip.AddressMask(s.Mask),182						Gateway:     tcpip.Address(ipToAddress(ip)),183						NIC:         nic1,184					}185					if got := routes.IsSameRoute(route1, route1); got != true {186						t.Fatalf("got IsSameRoute(%v, %v) = %v, want = %v", route1, route1, got, true)187					}188					// Change the NIC189					route2 := route1190					route2.NIC = route1.NIC + 1191					if got := routes.IsSameRoute(route1, route2); got != false {192						t.Errorf("got IsSameRoute(%v, %v) = %v, want = %v", route1, route2, got, false)193					}194					// Change destination.195					route2 = route1196					route2.Destination = tcpip.Address(changeByte([]byte(route2.Destination)))197					if got := routes.IsSameRoute(route1, route2); got != false {198						t.Errorf("got IsSameRoute(%v, %v) = %v, want = %v", route1, route2, got, false)199					}200					// Change gateway.201					route2 = route1202					route2.Gateway = tcpip.Address(changeByte([]byte(route2.Gateway)))203					if got := routes.IsSameRoute(route1, route2); got != false {204						t.Errorf("got IsSameRoute(%v, %v) = %v, want = %v", route1, route2, got, false)205					}206					// Remove gateway if possible207					if !util.IsAny(route1.Gateway) {208						route2 = route1209						route2.Gateway = tcpip.Address("")210						if got := routes.IsSameRoute(route1, route2); got != false {211							t.Errorf("got IsSameRoute(%v, %v) = %v, want = %v", route1, route2, got, false)212						}213					}214				})215			}216		})217	}218}219func isSameRouteTableImpl(rt1, rt2 []routes.ExtendedRoute, checkAttributes bool) bool {220	if len(rt1) != len(rt2) {221		return false222	}223	for i, r1 := range rt1 {224		r2 := rt2[i]225		if !routes.IsSameRoute(r1.Route, r2.Route) {226			return false227		}228		if checkAttributes && (r1.Metric != r2.Metric || r1.MetricTracksInterface != r2.MetricTracksInterface || r1.Dynamic != r2.Dynamic || r1.Enabled != r2.Enabled) {229			return false230		}231	}232	return true233}234func isSameRouteTable(rt1, rt2 []routes.ExtendedRoute) bool {235	return isSameRouteTableImpl(rt1, rt2, true /* checkAttributes */)236}237func isSameRouteTableSkippingAttributes(rt1, rt2 []routes.ExtendedRoute) bool {238	return isSameRouteTableImpl(rt1, rt2, false /* checkAttributes */)239}240func TestAddRoute(t *testing.T) {241	for _, tc := range []struct {242		name  string243		order []int244	}{245		// different orders246		{"Add1", []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}},247		{"Add2", []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}},248		{"Add3", []int{5, 3, 9, 2, 6, 0, 7, 10, 1, 4, 8}},249		{"Add4", []int{6, 5, 7, 4, 8, 3, 9, 2, 10, 1, 0}},250		// different orders and duplicates251		{"Add5", []int{0, 0, 1, 2, 3, 4, 2, 5, 6, 7, 1, 8, 9, 10, 0}},252		{"Add6", []int{10, 9, 8, 4, 7, 6, 5, 2, 4, 3, 2, 1, 0, 5, 5}},253		{"Add7", []int{5, 3, 9, 2, 6, 0, 7, 10, 10, 1, 3, 4, 8}},254		{"Add8", []int{6, 6, 6, 5, 7, 4, 8, 3, 9, 9, 2, 7, 10, 1, 0}},255	} {256		t.Run(tc.name, func(t *testing.T) {257			// Create route table by adding all routes in the given order.258			tb := routes.RouteTable{}259			for _, j := range tc.order {260				r := testRouteTable[j]261				tb.AddRoute(r.Route, r.Metric, r.MetricTracksInterface, r.Dynamic, r.Enabled)262			}263			tableWanted := testRouteTable264			tableGot := tb.GetExtendedRouteTable()265			if len(tableGot) != len(tableWanted) {266				t.Fatalf("got len(table) = %v, want len(table) = %v", len(tableGot), len(tableWanted))267			}268			if !isSameRouteTable(tableGot, tableWanted) {269				t.Errorf("got\n%v, want\n%v", tableGot, tableWanted)270			}271		})272	}273	// Adding a route that already exists but with different dynamic/enabled274	// attributes will just overwrite the entry with the new attributes. The275	// position in the table stays the same.276	t.Run("Changing dynamic/enabled", func(t *testing.T) {277		tb := routes.RouteTable{}278		tb.Set(testRouteTable)279		for i, r := range testRouteTable {280			r.Dynamic = !r.Dynamic281			tb.AddRoute(r.Route, r.Metric, r.MetricTracksInterface, r.Dynamic, r.Enabled)282			tableWanted := testRouteTable283			tableGot := tb.GetExtendedRouteTable()284			if tableGot[i].Dynamic != r.Dynamic {285				t.Errorf("got tableGot[%d].Dynamic = %v, want %v", i, tableGot[i].Dynamic, r.Dynamic)286			}287			if !isSameRouteTableSkippingAttributes(tableGot, tableWanted) {288				t.Errorf("got\n%v, want\n%v", tableGot, tableWanted)289			}290			r.Enabled = !r.Enabled291			tb.AddRoute(r.Route, r.Metric, r.MetricTracksInterface, r.Dynamic, r.Enabled)292			tableGot = tb.GetExtendedRouteTable()293			if tableGot[i].Enabled != r.Enabled {294				t.Errorf("got tableGot[%d].Enabled = %v, want %v", i, tableGot[i].Enabled, r.Enabled)295			}296			if !isSameRouteTableSkippingAttributes(tableGot, tableWanted) {297				t.Errorf("got\n%v, want\n%v", tableGot, tableWanted)298			}299		}300	})301	// The metric is used as a tie-breaker when routes have the same prefix length302	t.Run("Changing metric", func(t *testing.T) {303		r0 := createRoute(1, "0.0.0.0/0", "192.168.1.1")304		r1 := createRoute(2, "0.0.0.0/0", "192.168.100.10")305		// 1.test - r0 gets lower metric.306		tb := routes.RouteTable{}307		tb.AddRoute(r0, 100, true, true, true)308		tb.AddRoute(r1, 200, true, true, true)309		tableGot := tb.GetExtendedRouteTable()310		if !routes.IsSameRoute(r0, tableGot[0].Route) || !routes.IsSameRoute(r1, tableGot[1].Route) {311			t.Errorf("got %v, %v, want %v, %v", tableGot[0].Route, tableGot[1].Route, r0, r1)312		}313		// 2.test - r1 gets lower metric.314		tb = routes.RouteTable{}315		tb.AddRoute(r0, 200, true, true, true)316		tb.AddRoute(r1, 100, true, true, true)317		tableGot = tb.GetExtendedRouteTable()318		if !routes.IsSameRoute(r0, tableGot[1].Route) || !routes.IsSameRoute(r1, tableGot[0].Route) {319			t.Errorf("got %v, %v, want %v, %v", tableGot[0].Route, tableGot[1].Route, r1, r0)320		}321	})322}323func TestDelRoute(t *testing.T) {324	for _, tc := range []struct {325		name  string326		order []int327	}{328		{"Del1", []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}},329		{"Del2", []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}},330		{"Del3", []int{6, 5, 7, 4, 8, 3, 9, 2, 10, 1, 0}},331		{"Del4", []int{0}},332		{"Del5", []int{1}},333		{"Del6", []int{9}},334		{"Del7", []int{0, 0, 1, 1, 5, 5, 9, 9, 10, 10}},335		{"Del8", []int{5, 8, 5, 0, 1, 9, 1, 5}},336	} {337		t.Run(tc.name, func(t *testing.T) {338			tb := routes.RouteTable{}339			tb.Set(testRouteTable)340			validRoutes := make([]bool, len(testRouteTable))341			for i := range validRoutes {342				validRoutes[i] = true343			}344			for _, d := range tc.order {345				toDel := testRouteTable[d]346				tb.DelRoute(toDel.Route)347				validRoutes[d] = false348			}349			tableGot := tb.GetExtendedRouteTable()350			tableWant := []routes.ExtendedRoute{}351			for i, valid := range validRoutes {352				if valid {353					tableWant = append(tableWant, testRouteTable[i])354				}355			}356			if !isSameRouteTable(tableGot, tableWant) {357				t.Errorf("got\n%v, want\n%v", tableGot, tableWant)358			}359		})360	}361}362func TestUpdateMetricByInterface(t *testing.T) {363	// Updating the metric for the an interface updates the metric for all routes364	// that track that interface.365	for nicid := tcpip.NICID(1); nicid <= 4; nicid++ {366		t.Run(fmt.Sprintf("Change-NIC-%d-metric-updates-route-metric", nicid), func(t *testing.T) {367			tb := routes.RouteTable{}368			tb.Set(testRouteTable)369			newMetric := routes.Metric(1000 + nicid)370			// Verify existing table does not use the new metric yet.371			tableGot := tb.GetExtendedRouteTable()372			for _, r := range tableGot {373				if r.Metric == newMetric {374					t.Fatalf("Error: r.Metric said to invalid value before test start")375				}376			}377			tb.UpdateMetricByInterface(nicid, newMetric)378			tableGot = tb.GetExtendedRouteTable()379			for _, r := range tableGot {380				if r.Route.NIC != nicid {381					continue382				}383				if !r.MetricTracksInterface && r.Metric == newMetric {384					t.Errorf("got MetricTracksInterface==false && Metric=%v, want metric!=%v", r.Metric, newMetric)385				}386				if r.MetricTracksInterface && r.Metric != newMetric {387					t.Errorf("got MetricTracksInterface==true && Metric=%v, want metric=%v", r.Metric, newMetric)388				}389			}390		})391	}392	// A metric change should trigger a re-sort of the routing table.393	t.Run(fmt.Sprint("Change-metric-resorts-table"), func(t *testing.T) {394		r0 := createRoute(0, "0.0.0.0/0", "192.168.1.1")395		r1 := createRoute(1, "0.0.0.0/0", "192.168.100.10")396		// Initially r0 has lower metric and is ahead in the table.397		tb := routes.RouteTable{}398		tb.AddRoute(r0, 100, true, true, true)399		tb.AddRoute(r1, 200, true, true, true)400		tableGot := tb.GetExtendedRouteTable()401		if !routes.IsSameRoute(r0, tableGot[0].Route) || !routes.IsSameRoute(r1, tableGot[1].Route) {402			t.Errorf("got %v, %v, want %v, %v", tableGot[0].Route, tableGot[1].Route, r0, r1)403		}404		// Lowering nic1's metric should be reflected in r1's metric and promote it405		// in the route table.406		tb.UpdateMetricByInterface(1, 50)407		tableGot = tb.GetExtendedRouteTable()408		if !routes.IsSameRoute(r0, tableGot[1].Route) || !routes.IsSameRoute(r1, tableGot[0].Route) {409			t.Errorf("got %v, %v, want %v, %v", tableGot[0].Route, tableGot[1].Route, r1, r0)410		}411	})412}413func TestUpdateRoutesByInterface(t *testing.T) {414	for nicid := tcpip.NICID(1); nicid <= 4; nicid++ {415		// Test the normal case where on DOWN netstack removes dynamic routes and416		// disables static ones (ActionDeleteDynamicDisableStatic), and on up417		// it re-enables static routes (ActionEnableStatic).418		t.Run(fmt.Sprintf("Down-Up_NIC-%d", nicid), func(t *testing.T) {419			tb := routes.RouteTable{}420			tb.Set(testRouteTable)421			tableGot := tb.GetExtendedRouteTable()422			for _, r := range tableGot {423				if !r.Enabled {424					t.Errorf("Error: Route %v is disabled before test start", r)425				}426			}427			// Down -> Remove dynamic routes and disable static ones.428			tb.UpdateRoutesByInterface(nicid, routes.ActionDeleteDynamicDisableStatic)429			// Verify all dynamic routes to this NIC are gone, and static ones are430			// disabled.431			tableGot = tb.GetExtendedRouteTable()432			for _, r := range tableGot {433				if r.Route.NIC != nicid {434					continue435				}436				if r.Enabled {437					t.Errorf("got %v = enabled, want = disabled", r)438				}439				if r.Dynamic {440					t.Errorf("got dynamic %v, want it removed", r.Metric)441				}442			}443			// Up -> Re-enable static routes.444			tb.UpdateRoutesByInterface(nicid, routes.ActionEnableStatic)445			// Verify dynamic routes to this NIC are still gone, and static ones are446			// enabled.447			tableGot = tb.GetExtendedRouteTable()448			for _, r := range tableGot {449				if r.Route.NIC != nicid {450					continue451				}452				if !r.Enabled {453					t.Errorf("got %v = enabled, want = disabled", r)454				}455				if r.Dynamic {456					t.Errorf("got dynamic %v, want it removed", r.Metric)457				}458			}459		})460		// Test the special case where the interface is removed and in response all461		// routes to this interface are removed (ActionDeleteAll).462		t.Run(fmt.Sprintf("Remove_NIC-%d", nicid), func(t *testing.T) {463			tb := routes.RouteTable{}464			tb.Set(testRouteTable)465			tableGot := tb.GetExtendedRouteTable()466			for _, r := range tableGot {467				if !r.Enabled {468					t.Errorf("Error: Route %v is disabled before test start", r)469				}470			}471			// Remove all routes to nicid.472			tb.UpdateRoutesByInterface(nicid, routes.ActionDeleteAll)473			// Verify all routes to this NIC are gone.474			tableGot = tb.GetExtendedRouteTable()475			for _, r := range tableGot {476				if r.Route.NIC == nicid {477					t.Errorf("got route %v pointing to NIC-%d, want none", r, nicid)478				}479			}480		})481	}482}483func TestGetNetstackTable(t *testing.T) {484	for _, tc := range []struct {485		name     string486		disabled []int487	}{488		{"GetNsTable1", []int{}},489		{"GetNsTable2", []int{0}},490		{"GetNsTable3", []int{10}},491		{"GetNsTable4", []int{1}},492		{"GetNsTable5", []int{9}},493		{"GetNsTable6", []int{3, 5, 8}},494		{"GetNsTable7", []int{0, 1, 5, 6, 8, 9, 10}},495		{"GetNsTable8", []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}},496	} {497		t.Run(tc.name, func(t *testing.T) {498			// We have no way to directly disable routes in the route table, but we499			// can use the Set() command to set a table with pre-disabled routes.500			testRouteTable2 := make([]routes.ExtendedRoute, len(testRouteTable))501			copy(testRouteTable2, testRouteTable)502			// Disable a few routes.503			for _, i := range tc.disabled {504				testRouteTable2[i].Enabled = false505			}506			tb := routes.RouteTable{}507			tb.Set(testRouteTable2)508			tableGot := tb.GetNetstackTable()509			// Verify no disabled routes are in the Netstack table we got.510			i := 0511			for _, r := range testRouteTable2 {512				if r.Enabled {513					if !routes.IsSameRoute(tableGot[i], r.Route) {514						t.Errorf("got = %v, want = %v", tableGot[i], r.Route)515					}516					i += 1517				}518			}519		})520	}521}522func TestFindNIC(t *testing.T) {523	for _, tc := range []struct {524		name      string525		addr      string526		nicWanted tcpip.NICID // 0 means not found527	}{528		{"FindNic1", "127.0.0.1", 1},529		{"FindNic2", "127.0.0.0", 0},530		{"FindNic3", "192.168.1.234", 4},531		{"FindNic4", "192.168.1.1", 4},532		{"FindNic5", "192.168.2.1", 0},533		{"FindNic6", "192.168.100.1", 2},534		{"FindNic7", "192.168.100.10", 2},535		{"FindNic8", "192.168.101.10", 0},536		{"FindNic9", "10.1.2.1", 3},537		{"FindNic10", "10.1.3.1", 3},538		{"FindNic11", "10.1.4.1", 0},539	} {540		t.Run(tc.name, func(t *testing.T) {541			tb := routes.RouteTable{}542			tb.Set(testRouteTable)543			nicGot, err := tb.FindNIC(ipStringToAddress(tc.addr))544			if err != nil && tc.nicWanted > 0 {545				t.Errorf("got nic = <unknown>, want = %v", tc.nicWanted)546			} else if err == nil && tc.nicWanted != nicGot {547				t.Errorf("got nic = %d, want = %v", nicGot, tc.nicWanted)548			}549		})550	}551}...

Full Screen

Full Screen

resource_stackpath_compute_vpc_route_test.go

Source:resource_stackpath_compute_vpc_route_test.go Github

copy

Full Screen

...10	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"11	"github.com/stackpath/terraform-provider-stackpath/stackpath/api/ipam/ipam_client/virtual_private_cloud"12	"github.com/stackpath/terraform-provider-stackpath/stackpath/api/ipam/ipam_models"13)14func TestAccComputeVPCRoute(t *testing.T) {15	t.Parallel()16	route := &ipam_models.NetworkRoute{}17	resource.Test(t, resource.TestCase{18		ProviderFactories: testAccProviderFactories,19		PreCheck: func() {20			testAccPreCheck(t)21		},22		CheckDestroy: testAccComputeRouteCheckDestroy(),23		Steps: []resource.TestStep{24			{25				Config: `26				resource "stackpath_compute_vpc_network" "net" {27					name = "Test network"28					slug = "test-tf-network-1"29					root_subnet = "10.0.0.0/8"30				}31				// Create new route from slug and name32				resource "stackpath_compute_vpc_route" "foo" {33					name = "test-tf-route-1"34					slug = "test-tf-route-1"35					network_id = stackpath_compute_vpc_network.net.slug36					destination_prefixes = ["11.0.0.0/8"]37					gateway_selectors {38						interface_selectors {39							key = "workload.platform.stackpath.net/workload-slug"40							operator = "in"41							values = ["test"]42						}43					}44				}`,45				Check: resource.ComposeTestCheckFunc(46					testAccComputeCheckRouteExists("stackpath_compute_vpc_route.foo", route),47					testAccCheckRouteMatch(route, &ipam_models.NetworkRoute{48						Name:                "test-tf-route-1",49						Slug:                "test-tf-route-1",50						DestinationPrefixes: []string{"11.0.0.0/8"},51						GatewaySelectors: []*ipam_models.RouteGatewaySelector{52							{53								InterfaceSelectors: []*ipam_models.NetworkMatchExpression{54									{55										Key:      "workload.platform.stackpath.net/workload-slug",56										Operator: "in",57										Values:   []string{"test"},58									},59								},60							},61						},62						Metadata: &ipam_models.NetworkMetadata{63							Version: "1",64							Annotations: map[string]string{65								"ipam.platform.stackpath.net/network-slug": "test-tf-network-1",66							},67						},68					}),69				),70			},71			{72				Config: `73				resource "stackpath_compute_vpc_network" "net" {74					name = "Test network"75					slug = "test-tf-network-1"76					root_subnet = "10.0.0.0/8"77				}78				resource "stackpath_compute_vpc_route" "foo" {79					name = "test-tf-route-1"80					slug = "test-tf-route-1"81					network_id = stackpath_compute_vpc_network.net.slug82					destination_prefixes = ["13.0.0.0/8"] // Update prefix83					gateway_selectors {84						interface_selectors {85							key = "workload.platform.stackpath.net/workload-slug"86							operator = "in"87							values = ["test"]88						}89					}90				}`,91				Check: resource.ComposeTestCheckFunc(92					testAccComputeCheckRouteExists("stackpath_compute_vpc_route.foo", route),93					testAccCheckRouteMatch(route, &ipam_models.NetworkRoute{94						Name:                "test-tf-route-1",95						Slug:                "test-tf-route-1",96						DestinationPrefixes: []string{"13.0.0.0/8"},97						GatewaySelectors: []*ipam_models.RouteGatewaySelector{98							{99								InterfaceSelectors: []*ipam_models.NetworkMatchExpression{100									{101										Key:      "workload.platform.stackpath.net/workload-slug",102										Operator: "in",103										Values:   []string{"test"},104									},105								},106							},107						},108						Metadata: &ipam_models.NetworkMetadata{109							Version: "2",110							Annotations: map[string]string{111								"ipam.platform.stackpath.net/network-slug": "test-tf-network-1",112							},113						},114					}),115				),116			},117		},118	})119}120func testAccCheckRouteMatch(got, want *ipam_models.NetworkRoute) resource.TestCheckFunc {121	return func(s *terraform.State) error {122		if want == nil && got != nil {123			return errors.New("mismatch route. got=non-nil want=nil")124		}125		if want != nil && got == nil {126			return errors.New("mismatch route. got=nil want=non-nil")127		}128		if want.Name != got.Name {129			return fmt.Errorf("mismatch route.Name. got=%s want=%s", got.Name, want.Name)130		}131		if want.Slug != got.Slug {132			return fmt.Errorf("mismatch route.Slug. got=%s want=%s", got.Slug, want.Slug)133		}134		if !reflect.DeepEqual(want.DestinationPrefixes, got.DestinationPrefixes) {135			return fmt.Errorf("mismatch route.DestinationPrefixes. got=%#v want=%#v", got.DestinationPrefixes, want.DestinationPrefixes)136		}137		if want.Metadata == nil && got.Metadata != nil {138			return errors.New("mismatch route.Metadata. got=non-nil want=nil")139		}140		if want.Metadata != nil && got.Metadata == nil {141			return errors.New("mismatch route.Metadata. got=nil want=non-nil")142		}143		if want.Metadata != nil {144			if want.Metadata.Version != got.Metadata.Version {145				return fmt.Errorf("mismatch route.Metadata.Version. got=%s want=%s", got.Metadata.Version, want.Metadata.Version)146			}147			if !reflect.DeepEqual(want.Metadata.Labels, got.Metadata.Labels) {148				return fmt.Errorf("mismatch route.Metadata.Labels. got=%#v want=%#v", got.Metadata.Labels, want.Metadata.Labels)149			}150			if !reflect.DeepEqual(want.Metadata.Annotations, got.Metadata.Annotations) {151				return fmt.Errorf("mismatch route.Metadata.Annotations. got=%#v want=%#v", got.Metadata.Annotations, want.Metadata.Annotations)152			}153		}154		return nil155	}156}157func testAccComputeCheckRouteExists(name string, route *ipam_models.NetworkRoute) resource.TestCheckFunc {158	return func(s *terraform.State) error {159		rs, ok := s.RootModule().Resources[name]160		if !ok {161			return fmt.Errorf("resource not found: %s: available resources: %v", name, s.RootModule().Resources)162		}163		if rs.Primary.ID == "" {164			return fmt.Errorf("no ID set: %s", name)165		}166		config := testAccProvider.Meta().(*Config)167		params := virtual_private_cloud.GetRouteParams{168			StackID: config.StackID,169			Context: context.Background(),170		}171		var err error172		params.NetworkID, params.RouteID, err = parseRouteID(rs.Primary.ID)173		if err != nil {174			return fmt.Errorf("could not retrieve network: %v", err)175		}176		found, err := config.edgeComputeNetworking.VirtualPrivateCloud.GetRoute(&params, nil)177		if err != nil {178			return fmt.Errorf("could not retrieve network: %v", err)179		}180		*route = *found.Payload.Route181		return nil182	}183}184func testAccComputeRouteCheckDestroy() resource.TestCheckFunc {185	return func(s *terraform.State) error {186		config := testAccProvider.Meta().(*Config)187		for _, rs := range s.RootModule().Resources {188			if rs.Type != "stackpath_compute_vpc_route" {189				continue190			}191			params := virtual_private_cloud.GetRouteParams{192				StackID: config.StackID,193				Context: context.Background(),194			}195			fmt.Sscanf(rs.Primary.ID, "%s/%s", params.NetworkID, params.RouteID)196			resp, err := config.edgeComputeNetworking.VirtualPrivateCloud.GetRoute(&params, nil)197			// Since compute workloads are deleted asynchronously, we want to look at the fact that198			// the deleteRequestedAt timestamp was set on the workload. This field is used to indicate199			// that the workload is being deleted.200			if err == nil && *resp.Payload.Route.Metadata.DeleteRequestedAt == strfmt.NewDateTime() {201				return fmt.Errorf("route still exists: %v", rs.Primary.ID)202			}203		}204		return nil205	}206}...

Full Screen

Full Screen

analysis_test.go

Source:analysis_test.go Github

copy

Full Screen

...10	g, _, err := osgraphtest.BuildGraph("../../../api/graph/test/missing-route-port.yaml")11	if err != nil {12		t.Fatalf("unexpected error: %v", err)13	}14	routeedges.AddAllRouteEdges(g)15	markers := FindPortMappingIssues(g, osgraph.DefaultNamer)16	if expected, got := 1, len(markers); expected != got {17		t.Fatalf("expected %d markers, got %d", expected, got)18	}19	if expected, got := MissingRoutePortWarning, markers[0].Key; expected != got {20		t.Fatalf("expected %s marker key, got %s", expected, got)21	}22	// Dangling route23	g, _, err = osgraphtest.BuildGraph("../../../api/graph/test/lonely-route.yaml")24	if err != nil {25		t.Fatalf("unexpected error: %v", err)26	}27	routeedges.AddAllRouteEdges(g)28	markers = FindPortMappingIssues(g, osgraph.DefaultNamer)29	if expected, got := 1, len(markers); expected != got {30		t.Fatalf("expected %d markers, got %d", expected, got)31	}32	if expected, got := MissingServiceWarning, markers[0].Key; expected != got {33		t.Fatalf("expected %s marker key, got %s", expected, got)34	}35	// Wrong named route port36	g, _, err = osgraphtest.BuildGraph("../../../api/graph/test/wrong-numeric-port.yaml")37	if err != nil {38		t.Fatalf("unexpected error: %v", err)39	}40	routeedges.AddAllRouteEdges(g)41	markers = FindPortMappingIssues(g, osgraph.DefaultNamer)42	if expected, got := 1, len(markers); expected != got {43		t.Fatalf("expected %d markers, got %d", expected, got)44	}45	if expected, got := WrongRoutePortWarning, markers[0].Key; expected != got {46		t.Fatalf("expected %s marker key, got %s", expected, got)47	}48	// Wrong numeric route port49	g, _, err = osgraphtest.BuildGraph("../../../api/graph/test/wrong-named-port.yaml")50	if err != nil {51		t.Fatalf("unexpected error: %v", err)52	}53	routeedges.AddAllRouteEdges(g)54	markers = FindPortMappingIssues(g, osgraph.DefaultNamer)55	if expected, got := 1, len(markers); expected != got {56		t.Fatalf("expected %d markers, got %d", expected, got)57	}58	if expected, got := WrongRoutePortWarning, markers[0].Key; expected != got {59		t.Fatalf("expected %s marker key, got %s", expected, got)60	}61}62func TestPathBasedPassthroughRoutes(t *testing.T) {63	g, _, err := osgraphtest.BuildGraph("../../../api/graph/test/invalid-route.yaml")64	if err != nil {65		t.Fatalf("unexpected error: %v", err)66	}67	routeedges.AddAllRouteEdges(g)68	markers := FindPathBasedPassthroughRoutes(g, osgraph.DefaultNamer)69	if expected, got := 1, len(markers); expected != got {70		t.Fatalf("expected %d markers, got %d", expected, got)71	}72	if expected, got := PathBasedPassthroughErr, markers[0].Key; expected != got {73		t.Fatalf("expected %s marker key, got %s", expected, got)74	}75}76func TestMissingRouter(t *testing.T) {77	g, _, err := osgraphtest.BuildGraph("../../../api/graph/test/lonely-route.yaml")78	if err != nil {79		t.Fatalf("unexpected error: %v", err)80	}81	routeedges.AddAllRouteEdges(g)82	markers := FindMissingRouter(g, osgraph.DefaultNamer)83	if expected, got := 1, len(markers); expected != got {84		t.Fatalf("expected %d markers, got %d", expected, got)85	}86	if expected, got := MissingRequiredRouterErr, markers[0].Key; expected != got {87		t.Fatalf("expected %s marker key, got %s", expected, got)88	}89}...

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import (2func main() {3    r := mux.NewRouter()4    r.HandleFunc("/", HomeHandler)5    http.Handle("/", r)6    http.ListenAndServe(":8080", nil)7}8func HomeHandler(w http.ResponseWriter, r *http.Request) {9    fmt.Fprintf(w, "Welcome to the home page!")10}11import (12func main() {13    http.HandleFunc("/", HomeHandler)14    http.ListenAndServe(":8080", nil)15}16func HomeHandler(w http.ResponseWriter, r *http.Request) {17    fmt.Fprintf(w, "Welcome to the home page!")18}19import (20func main() {21    http.Handle("/", http.HandlerFunc(HomeHandler))22    http.ListenAndServe(":8080", nil)23}24func HomeHandler(w http.ResponseWriter, r *http.Request) {25    fmt.Fprintf(w, "Welcome to the home page!")26}27import (28func main() {29    http.Handle("/", &HomeHandler{})30    http.ListenAndServe(":8080", nil)31}32type HomeHandler struct{}33func (h *HomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {34    fmt.Fprintf(w, "Welcome to the home page!")35}36import (37func main() {38    http.Handle("/", HomeHandler{})39    http.ListenAndServe(":8080", nil)40}41type HomeHandler struct{}42func (h HomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {43    fmt.Fprintf(w, "Welcome to the home page!")44}45import (46func main() {47    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {48        fmt.Fprintf(w, "Welcome to the home page!")49    })

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	r := mux.NewRouter()4	r.HandleFunc("/", index)5	r.HandleFunc("/about", about)6	http.Handle("/", r)7	http.ListenAndServe(":3000", nil)8}9func index(w http.ResponseWriter, r *http.Request) {10	fmt.Fprintln(w, "Welcome!")11}12func about(w http.ResponseWriter, r *http.Request) {13	fmt.Fprintln(w, "About!")14}15import (16func main() {17	r := mux.NewRouter()18	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("assets"))))19	http.Handle("/", r)20	http.ListenAndServe(":3000", nil)21}22import (23func main() {24	r := mux.NewRouter()25	r.HandleFunc("/users/{name}/{id:[0-9]+}", func(w http.ResponseWriter, r *http.Request) {26		vars := mux.Vars(r)27		fmt.Fprintln(w, "Name: "+name+", ID: "+id)28	})29	http.Handle("/", r)30	http.ListenAndServe(":3000", nil)31}32import (33func main() {34	r := mux.NewRouter()35	r.Host("www.example.com").Path("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {36		fmt.Fprintln(w, "Welcome to example.com!")37	})38	http.Handle("/", r)39	http.ListenAndServe(":3000", nil)40}41import (42func main() {43	r := mux.NewRouter()44	r.Schemes("https").Host("www.example.com").Path("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/gorilla/mux"3func main() {4    r := mux.NewRouter()5    r.HandleFunc("/", HomeHandler)6    r.HandleFunc("/articles/{category}/", CategoryHandler)7    r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)8    http.Handle("/", r)9}10func HomeHandler(w http.ResponseWriter, r *http.Request) {11    fmt.Fprintf(w, "Welcome to the home page!")12}13func CategoryHandler(w http.ResponseWriter, r *http.Request) {14    vars := mux.Vars(r)15    w.WriteHeader(http.StatusOK)16    fmt.Fprintf(w, "Category: %v17}18func ArticleHandler(w http.ResponseWriter, r *http.Request) {19    vars := mux.Vars(r)20    w.WriteHeader(http.StatusOK)21    fmt.Fprintf(w, "Category: %v22    fmt.Fprintf(w, "ID: %v23}24import "fmt"25import "github.com/gorilla/mux"26func main() {27    r := mux.NewRouter()28    r.HandleFunc("/", HomeHandler)29    r.HandleFunc("/articles/{category}/", CategoryHandler)30    r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)31    http.Handle("/", r)32}33func HomeHandler(w http.ResponseWriter, r *http.Request) {34    fmt.Fprintf(w, "Welcome to the home page!")35}36func CategoryHandler(w http.ResponseWriter, r *http.Request) {37    vars := mux.Vars(r)38    w.WriteHeader(http.StatusOK)39    fmt.Fprintf(w, "Category: %v40}41func ArticleHandler(w http.ResponseWriter, r *http.Request) {42    vars := mux.Vars(r)43    w.WriteHeader(http.StatusOK)44    fmt.Fprintf(w, "Category: %v45    fmt.Fprintf(w, "ID: %v46}47import "fmt"48import "github.com/gorilla/mux"49func main() {50    r := mux.NewRouter()51    r.HandleFunc("/", HomeHandler)52    r.HandleFunc("/articles/{category}/", CategoryHandler)53    r.HandleFunc("/articles/{category}/{id:[0-

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	router := mux.NewRouter()4	router.HandleFunc("/get", get).Methods("GET")5	router.HandleFunc("/post", post).Methods("POST")6	router.HandleFunc("/put", put).Methods("PUT")7	router.HandleFunc("/delete", delete).Methods("DELETE")8	http.ListenAndServe(":8000", router)9}10func get(w http.ResponseWriter, r *http.Request) {11	fmt.Fprintln(w, "Get method")12}13func post(w http.ResponseWriter, r *http.Request) {14	fmt.Fprintln(w, "Post method")15}16func put(w http.ResponseWriter, r *http.Request) {17	fmt.Fprintln(w, "Put method")18}19func delete(w http.ResponseWriter, r *http.Request) {20	fmt.Fprintln(w, "Delete method")21}

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3    got := &got{}4    got.Route()5}6import "fmt"7func main() {8    got := &got{}9    got.Route()10}11import "fmt"12func main() {13    got := &got{}14    got.Route()15}16import "fmt"17func main() {18    got := &got{}19    got.Route()20}21import "fmt"22func main() {23    got := &got{}24    got.Route()25}26import "fmt"27func main() {28    got := &got{}29    got.Route()30}31import "fmt"32func main() {33    got := &got{}34    got.Route()35}36import "fmt"37func main() {38    got := &got{}39    got.Route()40}41import "fmt"42func main() {43    got := &got{}44    got.Route()45}46import "fmt"47func main() {48    got := &got{}49    got.Route()50}51import "fmt"52func main() {53    got := &got{}54    got.Route()55}56import "fmt"57func main() {58    got := &got{}59    got.Route()60}61import "fmt"62func main() {63    got := &got{}64    got.Route()65}

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3	got := new(Got)4	got.Route()5}6import "fmt"7func main() {8	got := new(Got)9	got.Route()10}11import "fmt"12func main() {13	got := new(Got)14	got.Route()15}16import "fmt"17func main() {18	got := new(Got)19	got.Route()20}21import "fmt"22func main() {23	got := new(Got)24	got.Route()25}26import "fmt"27func main() {28	got := new(Got)29	got.Route()30}31import "fmt"32func main() {33	got := new(Got)34	got.Route()35}36import "fmt"37func main() {38	got := new(Got)39	got.Route()40}41import "fmt"42func main() {43	got := new(Got)44	got.Route()45}46import "fmt"47func main() {48	got := new(Got)49	got.Route()50}51import "fmt"52func main() {53	got := new(Got)54	got.Route()55}56import "fmt"57func main() {58	got := new(Got)59	got.Route()60}61import "fmt"62func main() {63	got := new(Got)

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1func main() {2    got := got.New()3    got.Route("GET", "/", func(w http.ResponseWriter, r *http.Request) {4        w.Write([]byte("Hello World"))5    })6    got.Listen(":3000")7}8func main() {9    got := got.New()10    got.Get("/", func(w http.ResponseWriter, r *http.Request) {11        w.Write([]byte("Hello World"))12    })13    got.Listen(":3000")14}15func main() {16    got := got.New()17    got.Post("/", func(w http.ResponseWriter, r *http.Request) {18        w.Write([]byte("Hello World"))19    })20    got.Listen(":3000")21}22func main() {23    got := got.New()24    got.Put("/", func(w http.ResponseWriter, r *http.Request) {25        w.Write([]byte("Hello World"))26    })27    got.Listen(":3000")28}29func main() {30    got := got.New()31    got.Delete("/", func(w http.ResponseWriter, r *http.Request) {32        w.Write([]byte("Hello World"))33    })34    got.Listen(":3000")35}36func main() {37    got := got.New()38    got.Patch("/", func(w http.ResponseWriter, r *http.Request) {39        w.Write([]byte("Hello World"))40    })41    got.Listen(":3000")42}43func main() {44    got := got.New()45    got.Options("/", func(w http.ResponseWriter, r *http.Request) {46        w.Write([]byte("Hello World"))47    })48    got.Listen(":3000")49}50func main() {51    got := got.New()52    got.Head("/", func(w http.ResponseWriter, r *http.Request) {53        w.Write([]byte("Hello World"))54    })55    got.Listen(":3000")56}57func main() {

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1func main() {2    got := got.New()3    got.Route("/ping", func (w http.ResponseWriter, r *http.Request) {4        w.Write([]byte("pong"))5    })6    http.ListenAndServe(":3000", got)7}8func main() {9    got := got.New()10    got.Get("/ping", func (w http.ResponseWriter, r *http.Request) {11        w.Write([]byte("pong"))12    })13    got.Post("/ping", func (w http.ResponseWriter, r *http.Request) {14        w.Write([]byte("pong"))15    })16    got.Put("/ping", func (w http.ResponseWriter, r *http.Request) {17        w.Write([]byte("pong"))18    })19    got.Delete("/ping", func (w http.ResponseWriter, r *http.Request) {20        w.Write([]byte("pong"))21    })22    http.ListenAndServe(":3000", got)23}24func main() {25    got := got.New()26    got.Get("/ping", ping)27    got.Post("/ping", ping)28    got.Put("/ping", ping)29    got.Delete("/ping", ping)30    http.ListenAndServe(":3000", got)31}32func main() {33    got := got.New()34    got.Get("/ping", ping)35    got.Post("/ping", ping)36    got.Put("/ping", ping)37    got.Delete("/ping", ping)38    got.Get("/ping/:id", ping)39    got.Post("/ping/:id", ping)40    got.Put("/ping/:id", ping)41    got.Delete("/ping/:id", ping)42    got.Get("/ping/:id/:name", ping)43    got.Post("/ping/:id/:name", ping)44    got.Put("/ping/:id/:name", ping)45    got.Delete("/ping/:id/:name", ping)46    http.ListenAndServe(":3000", got)47}48func main() {49    got := got.New()50    got.Get("/ping", ping)51    got.Post("/ping", ping)52    got.Put("/

Full Screen

Full Screen

Route

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	route := got.Route("GET", "/users")4	fmt.Println(route)5}6import (7func Route(method string, path string) string {8	return fmt.Sprintf("%s %s", method, path)9}

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