Home > Article > Backend Development > How to set up proxy in golang
When using golang to make network requests, sometimes you need to access the target website through a proxy. Below we introduce how to set up a proxy in golang.
Use http proxy to automatically use the proxy when accessing http requests. The code is as follows:
func main() { proxyUrl, _ := url.Parse("http://127.0.0.1:8080") client := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyUrl), }, } resp, err := client.Get("http://www.baidu.com") if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
wherehttp. ProxyURL(proxyUrl)
can specify the proxy address, client.Get()
can initiate a network request.
If you need to access http and https requests at the same time, you can use the following code:
func main() { proxyUrl, _ := url.Parse("http://127.0.0.1:8080") client := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyUrl), TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, } resp, err := client.Get("https://www.baidu.com") if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
whereInsecureSkipVerify
Parameter is used to skip https certificate verification.
There are many advantages to using socks5 proxy, including better security and anonymity. The code is as follows:
func main() { dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:1080", nil, proxy.Direct) if err != nil { fmt.Println(err) return } httpClient := &http.Client{Transport: &http.Transport{Dial: dialer.Dial}} resp, err := httpClient.Get("http://www.google.com") if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
Among them, proxy.SOCKS5
can specify the socks5 proxy address, and httpClient.Get()
can initiate a network request.
Setting up agents is also an important part of network programming. After learning, you can better deal with actual situations.
The above is the detailed content of How to set up proxy in golang. For more information, please follow other related articles on the PHP Chinese website!