Proxy Server in Golang

Akash Jain
Aug 4 · 5 min read
Image for post
Image for post

What is a proxy Server?

Proxy means someone has the power or authority to do something for someone else or pretends to be someone else. Let us see this with a simple example, if you are living with Bob and currently he is not at home and you are alone and suppose the phone rang and you picked up the call and caller said, “Hi, this is Martin, may I speak to Bob”. As Bob was not at home so you pretended to be Bob and had a discussion with caller on behalf of Bob. So here, you are pretending to be Bob and caller is not aware that he is not speaking to Bob.

A Proxy server is simply a server that pretends to be an original server for clients.

Image for post
Image for post

Types of Proxy Server

Proxy servers are of different types based on the behaviour of the server. Some are mentioned below.

  • Forward Proxy

There are many more proxy servers. We will see some in detail.

Forward Proxy

A forward proxy is also called proxy by many people. This proxy acts on client-side. In this type of proxy, all requests from a client are sent to proxy server first and then that it perform some operations like logging, encryption, decryption, hide IP, etc. A firewall is a kind of forward proxy.

The use of a forward proxy is to bypass a network block i.e., run any web application that is restricted by the network.

Image for post
Image for post

Reverse Proxy

A reverse proxy is reverse to forward proxy, this proxy acts before the actual server. In this, all requests come from the client and goes to the internet and before going to the actual server it bypasses the reverse proxy server. This proxy perform operations like authentication, caching data, etc.

The use of a reverse proxy is to add security and hide the identity of the original server.

Image for post
Image for post

Use case of proxy

  • Cache content: Proxy servers can be used to cache content. If there are many GET requests then proxy server gets data from the original server and then cache it so that next time if same request comes then the proxy server will serve it own without the interference of original server.

Implement proxy server

Here we are going to build a load-balancing proxy server.

Load balancing is a kind of reverse proxy that sits in front of backend servers, receive the requests from the client and then distribute the request to any of the available servers.

Image for post
Image for post
  1. Defining all global variables and constant
var severCount = 0// These constant is used to define all backend servers
const (
SERVER1 = ""
SERVER2 = ""
SERVER3 = ""
PORT = "1338"

In reverse proxy we will be using a round-robin algorithm. We are using three backend servers behind a reverse proxy (load balancer). serverCount variable is integer kind, it will help to pick server one by one.

2. Define starting point of program, the main function.

func main() {
// start server
http.HandleFunc("/", loadBalacer)
log.Fatal(http.ListenAndServe(":" + PORT, nil))

We started a TCP server, all requests at this port are welcomed by this server and the load balancer is the handler for all requests. In this handler, we are going to write our main business logic.

3. Business logic inside the handler

// Given a request send it to the appropriate url
func loadBalacer(res http.ResponseWriter, req *http.Request) {
// Get address of one backend server on which we forward request
url := getProxyURL()
// Log the request
// Forward request to original request
serveReverseProxy(url, res, req)

getProxyURL() function is used to get servers address one by one.

// Balance returns one of the servers using round-robin algorithmfunc getProxyURL() string {
var servers = []string{SERVER1, SERVER2, SERVER3}
server := servers[severCount]
// reset the counter and start from the beginning
if severCount >= len(servers) {
severCount = 0
return server

logRequestPayload(url) function is used only to log the request in which the server (load balancer) is forwarding the request.

// Log the redirect url
func logRequestPayload(proxyURL string) {
log.Printf("proxy_url: %s\n", proxyURL)

serveReverseProxy function is the function where main logic of redirect has been written

// Serve a reverse proxy for a given url
func serveReverseProxy(target string, res http.ResponseWriter, req *http.Request) {
// parse the url
url, _ := url.Parse(target)
// create the reverse proxy
proxy := httputil.NewSingleHostReverseProxy(url)
// Note that ServeHttp is non blocking & uses a go routine under the hood
proxy.ServeHTTP(res, req)

NewSingleHostReverseProxy is the function in the httputil package, which returns ReverseProxy struct and then call ServeHTTP() where this package has the main logic of reverse proxy to forward a request to backend servers.

To know more about serverHTTP function, you can read this blog

Can visit this repo for whole codebase

So in the above example, we have created a load balancer proxy server.

The main objective of this article is to get familiar with basics of proxy server and using any logic we can create our own reverse proxy server in golang.

The Startup

Medium's largest active publication, followed by +731K people. Follow to join our community.

Akash Jain

Written by

Love to write code and discuss technology | If you explain others is simple words it means you know it very well

The Startup

Medium's largest active publication, followed by +731K people. Follow to join our community.

Akash Jain

Written by

Love to write code and discuss technology | If you explain others is simple words it means you know it very well

The Startup

Medium's largest active publication, followed by +731K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store