How to use Proxy method of got Package

Best Got code snippet using got.Proxy

main_test.go

Source:main_test.go Github

copy

Full Screen

...28	"testing"29	"time"30	"github.com/google/martian/mitm"31)32func waitForProxy(t *testing.T, c *http.Client, apiURL string) {33	timeout := 5 * time.Second34	deadline := time.Now().Add(timeout)35	for time.Now().Before(deadline) {36		res, err := c.Get(apiURL)37		if err != nil {38			time.Sleep(200 * time.Millisecond)39			continue40		}41		defer res.Body.Close()42		if got, want := res.StatusCode, http.StatusOK; got != want {43			t.Fatalf("waitForProxy: c.Get(%q): got status %d, want %d", apiURL, got, want)44		}45		return46	}47	t.Fatalf("waitForProxy: did not start up within %.1f seconds", timeout.Seconds())48}49// getFreePort returns a port string preceded by a colon, e.g. ":1234"50func getFreePort(t *testing.T) string {51	l, err := net.Listen("tcp", ":")52	if err != nil {53		t.Fatalf("getFreePort: could not get free port: %v", err)54	}55	defer l.Close()56	return l.Addr().String()[strings.LastIndex(l.Addr().String(), ":"):]57}58func parseURL(t *testing.T, u string) *url.URL {59	p, err := url.Parse(u)60	if err != nil {61		t.Fatalf("url.Parse(%q): got error %v, want no error", u, err)62	}63	return p64}65func TestProxyMain(t *testing.T) {66	tempDir, err := ioutil.TempDir("", t.Name())67	if err != nil {68		t.Fatal(err)69	}70	defer os.RemoveAll(tempDir)71	// Build proxy binary72	binPath := filepath.Join(tempDir, "proxy")73	cmd := exec.Command("go", "build", "-o", binPath)74	cmd.Stdout = os.Stdout75	cmd.Stderr = os.Stderr76	if err := cmd.Run(); err != nil {77		t.Fatal(err)78	}79	t.Run("Http", func(t *testing.T) {80		// Start proxy81		proxyPort := getFreePort(t)82		apiPort := getFreePort(t)83		cmd := exec.Command(binPath, "-addr="+proxyPort, "-api-addr="+apiPort)84		cmd.Stdout = os.Stdout85		cmd.Stderr = os.Stderr86		if err := cmd.Start(); err != nil {87			t.Fatal(err)88		}89		defer cmd.Wait()90		defer cmd.Process.Signal(os.Interrupt)91		proxyURL := "http://localhost" + proxyPort92		apiURL := "http://localhost" + apiPort93		configureURL := "http://martian.proxy/configure"94		// TODO: Make using API hostport directly work on Travis.95		apiClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(parseURL(t, apiURL))}}96		waitForProxy(t, apiClient, configureURL)97		// Configure modifiers98		config := strings.NewReader(`99			{100			  "fifo.Group": {101			    "scope": ["request", "response"],102			    "modifiers": [103			      {104			        "status.Modifier": {105			          "scope": ["response"],106			          "statusCode": 418107			        }108			      },109			      {110			        "skip.RoundTrip": {}111			      }112			    ]113			  }114			}`)115		res, err := apiClient.Post(configureURL, "application/json", config)116		if err != nil {117			t.Fatalf("apiClient.Post(%q): got error %v, want no error", configureURL, err)118		}119		defer res.Body.Close()120		if got, want := res.StatusCode, http.StatusOK; got != want {121			t.Fatalf("apiClient.Post(%q): got status %d, want %d", configureURL, got, want)122		}123		// Exercise proxy124		client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(parseURL(t, proxyURL))}}125		testURL := "http://super.fake.domain/"126		res, err = client.Get(testURL)127		if err != nil {128			t.Fatalf("client.Get(%q): got error %v, want no error", testURL, err)129		}130		defer res.Body.Close()131		if got, want := res.StatusCode, http.StatusTeapot; got != want {132			t.Errorf("client.Get(%q): got status %d, want %d", testURL, got, want)133		}134	})135	t.Run("HttpsGenerateCert", func(t *testing.T) {136		// Create test certificate for test TLS server137		certName := "martian.proxy"138		certOrg := "Martian Authority"139		certExpiry := 90 * time.Minute140		servCert, servPriv, err := mitm.NewAuthority(certName, certOrg, certExpiry)141		if err != nil {142			t.Fatalf("mitm.NewAuthority(%q, %q, %q): got error %v, want no error", certName, certOrg, certExpiry, err)143		}144		mc, err := mitm.NewConfig(servCert, servPriv)145		if err != nil {146			t.Fatalf("mitm.NewConfig(%p, %q): got error %v, want no error", servCert, servPriv, err)147		}148		sc := mc.TLS()149		// Configure and start test TLS server150		servPort := getFreePort(t)151		l, err := tls.Listen("tcp", servPort, sc)152		if err != nil {153			t.Fatalf("tls.Listen(\"tcp\", %q, %p): got error %v, want no error", servPort, sc, err)154		}155		defer l.Close()156		server := &http.Server{157			Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {158				w.WriteHeader(http.StatusTeapot)159				w.Write([]byte("Hello!"))160			}),161		}162		go server.Serve(l)163		defer server.Close()164		// Start proxy165		proxyPort := getFreePort(t)166		apiPort := getFreePort(t)167		cmd := exec.Command(binPath, "-addr="+proxyPort, "-api-addr="+apiPort, "-generate-ca-cert", "-skip-tls-verify")168		cmd.Stdout = os.Stdout169		cmd.Stderr = os.Stderr170		if err := cmd.Start(); err != nil {171			t.Fatal(err)172		}173		defer cmd.Wait()174		defer cmd.Process.Signal(os.Interrupt)175		proxyURL := "http://localhost" + proxyPort176		apiURL := "http://localhost" + apiPort177		configureURL := "http://martian.proxy/configure"178		// TODO: Make using API hostport directly work on Travis.179		apiClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(parseURL(t, apiURL))}}180		waitForProxy(t, apiClient, configureURL)181		// Configure modifiers182		config := strings.NewReader(fmt.Sprintf(`183			{184			  "body.Modifier": {185			    "scope": ["response"],186			    "contentType": "text/plain",187			    "body": "%s"188			  }189			}`, base64.StdEncoding.EncodeToString([]byte("茶壺"))))190		res, err := apiClient.Post(configureURL, "application/json", config)191		if err != nil {192			t.Fatalf("apiClient.Post(%q): got error %v, want no error", configureURL, err)193		}194		defer res.Body.Close()195		if got, want := res.StatusCode, http.StatusOK; got != want {196			t.Fatalf("apiClient.Post(%q): got status %d, want %d", configureURL, got, want)197		}198		// Install proxy's CA cert into http client199		caCertURL := "http://martian.proxy/authority.cer"200		res, err = apiClient.Get(caCertURL)201		if err != nil {202			t.Fatalf("apiClient.Get(%q): got error %v, want no error", caCertURL, err)203		}204		defer res.Body.Close()205		caCert, err := ioutil.ReadAll(res.Body)206		if err != nil {207			t.Fatalf("ioutil.ReadAll(res.Body): got error %v, want no error", err)208		}209		caCertPool := x509.NewCertPool()210		caCertPool.AppendCertsFromPEM(caCert)211		// Exercise proxy212		client := &http.Client{Transport: &http.Transport{213			Proxy: http.ProxyURL(parseURL(t, proxyURL)),214			TLSClientConfig: &tls.Config{215				RootCAs: caCertPool,216			},217		}}218		testURL := "https://localhost" + servPort219		res, err = client.Get(testURL)220		if err != nil {221			t.Fatalf("client.Get(%q): got error %v, want no error", testURL, err)222		}223		defer res.Body.Close()224		if got, want := res.StatusCode, http.StatusTeapot; got != want {225			t.Fatalf("client.Get(%q): got status %d, want %d", testURL, got, want)226		}227		body, err := ioutil.ReadAll(res.Body)228		if err != nil {229			t.Fatalf("ioutil.ReadAll(res.Body): got error %v, want no error", err)230		}231		if got, want := string(body), "茶壺"; got != want {232			t.Fatalf("modified response body: got %s, want %s", got, want)233		}234	})235	t.Run("DownstreamProxy", func(t *testing.T) {236		// Start downstream proxy237		dsProxyPort := getFreePort(t)238		dsAPIPort := getFreePort(t)239		cmd := exec.Command(binPath, "-addr="+dsProxyPort, "-api-addr="+dsAPIPort)240		cmd.Stdout = os.Stdout241		cmd.Stderr = os.Stderr242		if err := cmd.Start(); err != nil {243			t.Fatal(err)244		}245		defer cmd.Wait()246		defer cmd.Process.Signal(os.Interrupt)247		dsProxyURL := "http://localhost" + dsProxyPort248		dsAPIURL := "http://localhost" + dsAPIPort249		configureURL := "http://martian.proxy/configure"250		// TODO: Make using API hostport directly work on Travis.251		dsAPIClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(parseURL(t, dsAPIURL))}}252		waitForProxy(t, dsAPIClient, configureURL)253		// Configure modifiers254		config := strings.NewReader(`255			{256			  "fifo.Group": {257			    "scope": ["request", "response"],258			    "modifiers": [259			      {260			        "status.Modifier": {261			          "scope": ["response"],262			          "statusCode": 418263			        }264			      },265			      {266			        "skip.RoundTrip": {}267			      }268			    ]269			  }270			}`)271		res, err := dsAPIClient.Post(configureURL, "application/json", config)272		if err != nil {273			t.Fatalf("dsApiClient.Post(%q): got error %v, want no error", configureURL, err)274		}275		defer res.Body.Close()276		if got, want := res.StatusCode, http.StatusOK; got != want {277			t.Fatalf("dsApiClient.Post(%q): got status %d, want %d", configureURL, got, want)278		}279		// Start main proxy280		proxyPort := getFreePort(t)281		apiPort := getFreePort(t)282		cmd = exec.Command(binPath, "-addr="+proxyPort, "-api-addr="+apiPort, "-downstream-proxy-url="+dsProxyURL)283		cmd.Stdout = os.Stdout284		cmd.Stderr = os.Stderr285		if err := cmd.Start(); err != nil {286			t.Fatal(err)287		}288		defer cmd.Wait()289		defer cmd.Process.Signal(os.Interrupt)290		proxyURL := "http://localhost" + proxyPort291		apiURL := "http://localhost" + apiPort292		// TODO: Make using API hostport directly work on Travis.293		apiClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(parseURL(t, apiURL))}}294		waitForProxy(t, apiClient, configureURL)295		// Configure modifiers296		// Setting a different Via header value to circumvent loop detection.297		config = strings.NewReader(fmt.Sprintf(`298			{299			  "fifo.Group": {300			    "scope": ["request", "response"],301			    "modifiers": [302			      {303			        "header.Modifier": {304			          "scope": ["request"],305			          "name": "Via",306			          "value": "martian_1"307			        }308			      },309			      {310			        "body.Modifier": {311			          "scope": ["response"],312			          "contentType": "text/plain",313			          "body": "%s"314			        }315			      }316			    ]317			  }318			}`, base64.StdEncoding.EncodeToString([]byte("茶壺"))))319		res, err = apiClient.Post(configureURL, "application/json", config)320		if err != nil {321			t.Fatalf("apiClient.Post(%q): got error %v, want no error", configureURL, err)322		}323		defer res.Body.Close()324		if got, want := res.StatusCode, http.StatusOK; got != want {325			t.Fatalf("apiClient.Post(%q): got status %d, want %d", configureURL, got, want)326		}327		// Exercise proxy328		client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(parseURL(t, proxyURL))}}329		testURL := "http://super.fake.domain/"330		res, err = client.Get(testURL)331		if err != nil {332			t.Fatalf("client.Get(%q): got error %v, want no error", testURL, err)333		}334		defer res.Body.Close()335		if got, want := res.StatusCode, http.StatusTeapot; got != want {336			t.Errorf("client.Get(%q): got status %d, want %d", testURL, got, want)337		}338		body, err := ioutil.ReadAll(res.Body)339		if err != nil {340			t.Fatalf("ioutil.ReadAll(res.Body): got error %v, want no error", err)341		}342		if got, want := string(body), "茶壺"; got != want {...

Full Screen

Full Screen

proxy_test.go

Source:proxy_test.go Github

copy

Full Screen

...26		if buf.Len() > 0 {27			buf.WriteByte(' ')28		}29	}30	if t.cfg.HTTPProxy != "" {31		fmt.Fprintf(&buf, "http_proxy=%q", t.cfg.HTTPProxy)32	}33	if t.cfg.HTTPSProxy != "" {34		space()35		fmt.Fprintf(&buf, "https_proxy=%q", t.cfg.HTTPSProxy)36	}37	if t.cfg.NoProxy != "" {38		space()39		fmt.Fprintf(&buf, "no_proxy=%q", t.cfg.NoProxy)40	}41	req := "http://example.com"42	if t.req != "" {43		req = t.req44	}45	space()46	fmt.Fprintf(&buf, "req=%q", req)47	return strings.TrimSpace(buf.String())48}49var proxyForURLTests = []proxyForURLTest{{50	cfg: httpproxy.Config{51		HTTPProxy: "127.0.0.1:8080",52	},53	want: "http://127.0.0.1:8080",54}, {55	cfg: httpproxy.Config{56		HTTPProxy: "cache.corp.example.com:1234",57	},58	want: "http://cache.corp.example.com:1234",59}, {60	cfg: httpproxy.Config{61		HTTPProxy: "cache.corp.example.com",62	},63	want: "http://cache.corp.example.com",64}, {65	cfg: httpproxy.Config{66		HTTPProxy: "https://cache.corp.example.com",67	},68	want: "https://cache.corp.example.com",69}, {70	cfg: httpproxy.Config{71		HTTPProxy: "http://127.0.0.1:8080",72	},73	want: "http://127.0.0.1:8080",74}, {75	cfg: httpproxy.Config{76		HTTPProxy: "https://127.0.0.1:8080",77	},78	want: "https://127.0.0.1:8080",79}, {80	cfg: httpproxy.Config{81		HTTPProxy: "socks5://127.0.0.1",82	},83	want: "socks5://127.0.0.1",84}, {85	// Don't use secure for http86	cfg: httpproxy.Config{87		HTTPProxy:  "http.proxy.tld",88		HTTPSProxy: "secure.proxy.tld",89	},90	req:  "http://insecure.tld/",91	want: "http://http.proxy.tld",92}, {93	// Use secure for https.94	cfg: httpproxy.Config{95		HTTPProxy:  "http.proxy.tld",96		HTTPSProxy: "secure.proxy.tld",97	},98	req:  "https://secure.tld/",99	want: "http://secure.proxy.tld",100}, {101	cfg: httpproxy.Config{102		HTTPProxy:  "http.proxy.tld",103		HTTPSProxy: "https://secure.proxy.tld",104	},105	req:  "https://secure.tld/",106	want: "https://secure.proxy.tld",107}, {108	// Issue 16405: don't use HTTP_PROXY in a CGI environment,109	// where HTTP_PROXY can be attacker-controlled.110	cfg: httpproxy.Config{111		HTTPProxy: "http://10.1.2.3:8080",112		CGI:       true,113	},114	want:    "<nil>",115	wanterr: errors.New("refusing to use HTTP_PROXY value in CGI environment; see golang.org/s/cgihttpproxy"),116}, {117	// HTTPS proxy is still used even in CGI environment.118	// (perhaps dubious but it's the historical behaviour).119	cfg: httpproxy.Config{120		HTTPSProxy: "https://secure.proxy.tld",121		CGI:        true,122	},123	req:  "https://secure.tld/",124	want: "https://secure.proxy.tld",125}, {126	want: "<nil>",127}, {128	cfg: httpproxy.Config{129		NoProxy:   "example.com",130		HTTPProxy: "proxy",131	},132	req:  "http://example.com/",133	want: "<nil>",134}, {135	cfg: httpproxy.Config{136		NoProxy:   ".example.com",137		HTTPProxy: "proxy",138	},139	req:  "http://example.com/",140	want: "http://proxy",141}, {142	cfg: httpproxy.Config{143		NoProxy:   "ample.com",144		HTTPProxy: "proxy",145	},146	req:  "http://example.com/",147	want: "http://proxy",148}, {149	cfg: httpproxy.Config{150		NoProxy:   "example.com",151		HTTPProxy: "proxy",152	},153	req:  "http://foo.example.com/",154	want: "<nil>",155}, {156	cfg: httpproxy.Config{157		NoProxy:   ".foo.com",158		HTTPProxy: "proxy",159	},160	req:  "http://example.com/",161	want: "http://proxy",162}}163func testProxyForURL(t *testing.T, tt proxyForURLTest) {164	setHelper(t)165	reqURLStr := tt.req166	if reqURLStr == "" {167		reqURLStr = "http://example.com"168	}169	reqURL, err := url.Parse(reqURLStr)170	if err != nil {171		t.Errorf("invalid URL %q", reqURLStr)172		return173	}174	cfg := tt.cfg175	proxyForURL := cfg.ProxyFunc()176	url, err := proxyForURL(reqURL)177	if g, e := fmt.Sprintf("%v", err), fmt.Sprintf("%v", tt.wanterr); g != e {178		t.Errorf("%v: got error = %q, want %q", tt, g, e)179		return180	}181	if got := fmt.Sprintf("%s", url); got != tt.want {182		t.Errorf("%v: got URL = %q, want %q", tt, url, tt.want)183	}184	// Check that changing the Config doesn't change the results185	// of the functuon.186	cfg = httpproxy.Config{}187	url, err = proxyForURL(reqURL)188	if g, e := fmt.Sprintf("%v", err), fmt.Sprintf("%v", tt.wanterr); g != e {189		t.Errorf("(after mutating config) %v: got error = %q, want %q", tt, g, e)190		return191	}192	if got := fmt.Sprintf("%s", url); got != tt.want {193		t.Errorf("(after mutating config) %v: got URL = %q, want %q", tt, url, tt.want)194	}195}196func TestProxyForURL(t *testing.T) {197	for _, tt := range proxyForURLTests {198		testProxyForURL(t, tt)199	}200}201func TestFromEnvironment(t *testing.T) {202	os.Setenv("HTTP_PROXY", "httpproxy")203	os.Setenv("HTTPS_PROXY", "httpsproxy")204	os.Setenv("NO_PROXY", "noproxy")205	os.Setenv("REQUEST_METHOD", "")206	got := httpproxy.FromEnvironment()207	want := httpproxy.Config{208		HTTPProxy:  "httpproxy",209		HTTPSProxy: "httpsproxy",210		NoProxy:    "noproxy",211	}212	if *got != want {213		t.Errorf("unexpected proxy config, got %#v want %#v", got, want)214	}215}216func TestFromEnvironmentWithRequestMethod(t *testing.T) {217	os.Setenv("HTTP_PROXY", "httpproxy")218	os.Setenv("HTTPS_PROXY", "httpsproxy")219	os.Setenv("NO_PROXY", "noproxy")220	os.Setenv("REQUEST_METHOD", "PUT")221	got := httpproxy.FromEnvironment()222	want := httpproxy.Config{223		HTTPProxy:  "httpproxy",224		HTTPSProxy: "httpsproxy",225		NoProxy:    "noproxy",226		CGI:        true,227	}228	if *got != want {229		t.Errorf("unexpected proxy config, got %#v want %#v", got, want)230	}231}232func TestFromEnvironmentLowerCase(t *testing.T) {233	os.Setenv("http_proxy", "httpproxy")234	os.Setenv("https_proxy", "httpsproxy")235	os.Setenv("no_proxy", "noproxy")236	os.Setenv("REQUEST_METHOD", "")237	got := httpproxy.FromEnvironment()238	want := httpproxy.Config{239		HTTPProxy:  "httpproxy",240		HTTPSProxy: "httpsproxy",241		NoProxy:    "noproxy",242	}243	if *got != want {244		t.Errorf("unexpected proxy config, got %#v want %#v", got, want)245	}246}247var UseProxyTests = []struct {248	host  string249	match bool250}{251	// Never proxy localhost:252	{"localhost", false},253	{"127.0.0.1", false},254	{"127.0.0.2", false},255	{"[::1]", false},256	{"[::2]", true}, // not a loopback address257	{"192.168.1.1", false},                // matches exact IPv4258	{"192.168.1.2", true},                 // ports do not match259	{"192.168.1.3", false},                // matches exact IPv4:port260	{"192.168.1.4", true},                 // no match261	{"10.0.0.2", false},                   // matches IPv4/CIDR262	{"[2001:db8::52:0:1]", false},         // matches exact IPv6263	{"[2001:db8::52:0:2]", true},          // no match264	{"[2001:db8::52:0:3]", false},         // matches exact [IPv6]:port265	{"[2002:db8:a::123]", false},          // matches IPv6/CIDR266	{"[fe80::424b:c8be:1643:a1b6]", true}, // no match267	{"barbaz.net", true},          // does not match as .barbaz.net268	{"www.barbaz.net", false},     // does match as .barbaz.net269	{"foobar.com", false},         // does match as foobar.com270	{"www.foobar.com", false},     // match because NO_PROXY includes "foobar.com"271	{"foofoobar.com", true},       // not match as a part of foobar.com272	{"baz.com", true},             // not match as a part of barbaz.com273	{"localhost.net", true},       // not match as suffix of address274	{"local.localhost", true},     // not match as prefix as address275	{"barbarbaz.net", true},       // not match, wrong domain276	{"wildcard.io", true},         // does not match as *.wildcard.io277	{"nested.wildcard.io", false}, // match as *.wildcard.io278	{"awildcard.io", true},        // not a match because of '*'279}280var noProxy = "foobar.com, .barbaz.net, *.wildcard.io, 192.168.1.1, 192.168.1.2:81, 192.168.1.3:80, 10.0.0.0/30, 2001:db8::52:0:1, [2001:db8::52:0:2]:443, [2001:db8::52:0:3]:80, 2002:db8:a::45/64"281func TestUseProxy(t *testing.T) {282	cfg := &httpproxy.Config{283		NoProxy: noProxy,284	}285	for _, test := range UseProxyTests {286		if httpproxy.ExportUseProxy(cfg, test.host+":80") != test.match {287			t.Errorf("useProxy(%v) = %v, want %v", test.host, !test.match, test.match)288		}289	}290}291func TestInvalidNoProxy(t *testing.T) {292	cfg := &httpproxy.Config{293		NoProxy: ":1",294	}295	ok := httpproxy.ExportUseProxy(cfg, "example.com:80") // should not panic296	if !ok {297		t.Errorf("useProxy unexpected return; got false; want true")298	}299}300func TestAllNoProxy(t *testing.T) {301	cfg := &httpproxy.Config{302		NoProxy: "*",303	}304	for _, test := range UseProxyTests {305		if httpproxy.ExportUseProxy(cfg, test.host+":80") != false {306			t.Errorf("useProxy(%v) = true, want false", test.host)307		}308	}309}310func BenchmarkProxyForURL(b *testing.B) {311	cfg := &httpproxy.Config{312		HTTPProxy:  "http://proxy.example.org",313		HTTPSProxy: "https://proxy.example.org",314		NoProxy:    noProxy,315	}316	for _, test := range UseProxyTests {317		u, err := url.Parse("https://" + test.host + ":80")318		if err != nil {319			b.Fatalf("parsed failed: %s", test.host)320		}321		proxyFunc := cfg.ProxyFunc()322		b.Run(test.host, func(b *testing.B) {323			for n := 0; n < b.N; n++ {324				if au, e := proxyFunc(u); e != nil && test.match == (au != nil) {325					b.Errorf("useProxy(%v) = %v, want %v", test.host, !test.match, test.match)326				}327			}328		})329	}330}...

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func proxyHandler(w http.ResponseWriter, r *http.Request) {3	if err != nil {4		log.Fatal(err)5	}6	proxy := httputil.NewSingleHostReverseProxy(url)7	proxy.ServeHTTP(w, r)8}9func main() {10	fmt.Println("Proxy Server is running on port 8080")11	http.HandleFunc("/", proxyHandler)12	log.Fatal(http.ListenAndServe(":8080", nil))13}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	proxyStr := os.Getenv("http_proxy")4	if proxyStr == "" {5		proxyStr = os.Getenv("HTTP_PROXY")6	}7	proxyURL, err := url.Parse(proxyStr)8	if err != nil {9		fmt.Println("Error in parsing proxy URL")10	}11	transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}12	client := &http.Client{Transport: transport}13	if err != nil {14		fmt.Println("Error in GET")15	}16	fmt.Println(resp.Status)17}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	if err != ni" {4		panic(err)5	}6	defer res.Body.Close()7	if res.StatusCode != 200 {8		panic("status code error:  + res.Status)9	}10	doc, err := goquery.NewDocumentFromReader(res.Body)11	if err != nil {12		panic(err)13	}14	doc.Find(".sf-costtnr-block").Each(func(i int, s *goquery.Selection) {15		band := s.Find("h3").Texs()16		title := s.Find("a").Text()17		linkTag := s.Find("a")18		link, _ := linkTag.Attr("href")19		fmt.Printf("Review %d: %s - %s\n", i, band, title)20		fmt.Printf("Link: %s\n", link)21	})22}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	if err != nil {4		panic(err)5	}6	defer res.Body.Close()7	if res.StatusCode != 200 {8		panic("status code error: " + res.Status)9	}10	doc, err := goquery.NewDocumentFromReader(res.Body)11	if err != nil {12		panic(err)13	}14	doc.Find(".sf-content-block").Each(func(i int, s *goquery.Selection) {15		band := s.Find("h3").Text()16		title := s.Find("a").Text()17		linkTag := s.Find("a")18		link, _ := linkTag.Attr("href")19		fmt.Printf("Review %d: %s - %s\n", i, band, title)20		fmt.Printf("Link: %s\n", link)21	})22}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	proxy, err := http.ProxyFromEnvironment(http.DefaultTransport)4	if err != nil {5		fmt.Println(err)6	}7	if err != nil {8		fmt.Println(err)9	}10	resp, err := http.DefaultTransport.RoundTrip(req)11	if err != nil {12		fmt.Println(err)13	}14	body, err := ioutil.ReadAll(resp.Body)15	if err != nil {16		fmt.Println(err)17	}18	fmt.Println(string(body))19}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	request := gorequest.New()4	fmt.Println(resp)5	fmt.Println(body)6	fmt.Println(errs)7}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	g := got.NewGot()4	resp, err := proxy.Get("www.google.com")5	if err != nil {6		fmt.Println("error in getting response", err)7	}8	fmt.Println(resp)9}10import (11func main() {12	payload := strings.NewReader("Hello World")13	req, _ := http.NewRequest("POST", url, payload)14	req.Header.Add("content-type", "application/json")15	req.Header.Add("cache-control", "no-cache")16	res, _ := http.DefaultClient.Do(req)17	defer res.Body.Close()18	body, _ := ioutil.ReadAll(res.Body)19	fmt.Println(res)20	fmt.Println(string(body))21}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	if err != nil {4		fmt.Println(err)5		os.Exit(1)6	}

Full Screen

Full Screen

Proxy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	g := got.NewGot()4	resp, err := proxy.Get("www.google.com")5	if err != nil {6		fmt.Println("error in getting response", err)7	}8	fmt.Println(resp)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