Mar 52018

ADM

How to setup a proxy for HTTP client in Golang

  • March 5 2018
  • ADM

 

 

How to setup a proxy for HTTP client in Golang - golang

 

Here is a Golang example that calls an URL using an HTTP GET with proxy settings.

Code

package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

func main() {

	//creating the proxyURL
	proxyStr := "http://localhost:7000"
	proxyURL, err := url.Parse(proxyStr)
	if err != nil {
		log.Println(err)
	}

	//creating the URL to be loaded through the proxy
	urlStr := "http://httpbin.org/get"
	url, err := url.Parse(urlStr)
	if err != nil {
		log.Println(err)
	}

	//adding the proxy settings to the Transport object
	transport := &http.Transport{
		Proxy: http.ProxyURL(proxyURL),
	}

	//adding the Transport object to the http Client
	client := &http.Client{
		Transport: transport,
	}

	//generating the HTTP GET request
	request, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		log.Println(err)
	}

	//calling the URL
	response, err := client.Do(request)
	if err != nil {
		log.Println(err)
	}

	//getting the response
	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Println(err)
	}
	//printing the response
	log.Println(string(data))
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build HTTPClientProxy.go

Then depending if you are on Linux or windows the binary file is created.

To run the application execute the command.

Linux

$ ./HTTPClientProxy

Windows

c:\Users\adm\go\tutorials>HTTPClientProxy.exe

Output

The output will print the response, a JSON string with details about the call.

2018/02/01 11:49:23 {
 "args": {},
 "headers": {
 "Accept-Encoding": "gzip",
 "Cache-Control": "max-age=259200",
 "Connection": "close",
 "Host": "httpbin.org",
 "User-Agent": "Go-http-client/1.1"
 },
 "origin": "5.93.200.201, 102.222.128.106",
 "url": "http://httpbin.org/get"
}

References