How to use Goland to use proxy IP for http requests


1. Customize Transport in http.Client and set Proxy.


   // No proxy authentication required, set directly: url.Parse("http://proxy IP (/domain name):proxy port")
   uri, err := url.Parse("http://authentication account:authentication password@proxy IP (/domain name):proxy port")
   if err != nil{
   log.Fatal("parse url error: ", err)
   }

   log.Println(uri.User)
   client := http.Client{
   Transport: &http.Transport{
   //Set proxy
   Proxy: http.ProxyURL(uri),
   },
   }
   //Initiate request
   resp, err := client.Get("http://www.baidu.com")
   if err != nil{
   log.Fatal(err)
   }
   defer resp.Body.Close()
   data, _ := ioutil.ReadAll(resp.Body)
   log.Println(string(data))



2. In addition, you can also set environment variables, such as: HTTP_PROXY, HTTPS_PROXY, NO_PROXY

Modify the code above


   client := http.Client{
   Transport: &http.Transport{
   //Set the proxy and get it from environment variables
   Proxy: http.ProxyFromEnvironment,
   },
   }
   //Initiate request
   resp, err := client.Get("http://www.baidu.com")
   if err != nil{
   log.Fatal(err)
   }
   defer resp.Body.Close()
   data, _ := ioutil.ReadAll(resp.Body)
   log.Println(string(data))


The above is a tutorial on how to use the go language to make simple requests.

[email protected]