Sling Academy
Home/Golang/Building Proxy Servers with Go

Building Proxy Servers with Go

Last updated: November 27, 2024

Introduction

Proxy servers are essential tools in network security, management, and can help improve access and load for applications. In this article, we will guide you through building a simple proxy server using the Go programming language, which is known for its efficiency and simplicity.

Prerequisites

Before starting, ensure you have Go installed on your machine. You can download it from the official website. Familiarity with basic Go programming is recommended.

Setting Up the Environment

First, set up a directory for your project:

mkdir go-proxy-server
cd go-proxy-server

Initialize a new Go module for dependency management:

go mod init go-proxy-server

Creating a Basic HTTP Proxy Server

Let's start by creating a basic HTTP proxy server. We’ll be using Go’s built-in net/http package. Create a new file named main.go and add the following code:

package main

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

func handleProxy(w http.ResponseWriter, r *http.Request) {
    r.Header.Del("Proxy-Connection")

    resp, err := http.DefaultTransport.RoundTrip(r)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadGateway)
        return
    }

    defer resp.Body.Close()

    copyHeader(w.Header(), resp.Header)
    w.WriteHeader(resp.StatusCode)
    io.Copy(w, resp.Body)
}

func copyHeader(dst, src http.Header) {
    for k, vv := range src {
        for _, v := range vv {
            dst.Add(k, v)
        }
    }
}

func main() {
    http.HandleFunc("/", handleProxy)

    log.Println("Starting proxy server on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatalf("ListenAndServe: %v", err)
    }
}

How It Works

In this code snippet, the handleProxy function handles requests forwarded by the proxy server. It removes the 'Proxy-Connection' header and then makes a request to the target server using Go's http.RoundTripper. The response body and headers are copied back to the client.

Running the Proxy Server

Now you can run your server:

go run main.go

This command will start the proxy server listening on port 8080. You can configure your browser or an HTTP client to use this proxy for requests.

Testing the Proxy Server

To test, set up your HTTP client or browser to use http://localhost:8080 as a proxy and try accessing a website. Observe the logs in your terminal.

Enhancements and Security

While our proxy server is functional, it is basic. Consider adding features like logging, access control, or HTTPS support for encryption and better security.

Additionally, using external libraries like GoProxy can provide more proxy functionalities without starting from scratch.

Conclusion

With minimal code, Go allows us to create robust network applications like proxy servers. By understanding how to forward and handle HTTP requests, you've built the foundation for more advanced features and optimizations.

Next Article: Rate Limiting and Traffic Control in Go Servers

Previous Article: Customizing Go HTTP Clients for Better Performance

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant