Menu Close

Go – HTTP ProxyURL Function in Go

In this article, we will explore the http ProxyURL function in Go net/http package in detail, along with examples.

One common task that many developers need to perform is proxying HTTP requests to other servers, which can be done using the ProxyURL function available in the http package.

A proxy server acts as an intermediary between a client and a server. The client sends requests to the proxy, which then forwards the requests to the target server. The server’s response is returned to the proxy, which forwards it back to the client. This can be useful for load balancing, security, or caching purposes.

The http.ProxyURL Function in Go

In Go, the http.Transport structure provides a field called Proxy, which is a function that takes an http.Request as an argument and returns a URL to be used as a proxy. The http.ProxyURL function can be used as a value for this field to specify a fixed proxy URL.

syntax

func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)

Example Usage

package main

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

func main() {
	proxyURL, _ := url.Parse("http://proxy.example.com:8080")

	transport := &http.Transport{
		Proxy: http.ProxyURL(proxyURL),
	}

	client := &http.Client{Transport: transport}

	resp, err := client.Get("http://example.com")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("Response:", string(body))
}

In this example, we create an http.Transport with the Proxy field set to the result of http.ProxyURL(proxyURL). We then create an http.Client using this custom transport and make an HTTP GET request. The request will be sent through the specified proxy server.

Breaking Down the Example

Import the necessary packages:

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

Parse the proxy URL:

proxyURL, _ := url.Parse("http://proxy.example.com:8080")

Create a custom http.Transport with the Proxy field set to the result of http.ProxyURL(proxyURL):

transport := &http.Transport{
	Proxy: http.ProxyURL(proxyURL),
}

Create an http.Client with the custom transport:

client := &http.Client{Transport: transport}

Make an HTTP GET request using the client:

resp, err := client.Get("http://example.com")

Handle the response:

if err != nil {
	fmt.Println("Error:", err)
	return
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))

To check more Go related articles. Pls click given below link:

https://www.techieindoor.com/go-net-http-package-in-go-golang/

https://pkg.go.dev/net/http

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *