Sling Academy
Home/Golang/How to create a simple proxy server with Go

How to create a simple proxy server with Go

Last updated: November 27, 2024

A proxy server acts as an intermediary for requests from clients seeking resources from other servers. Creating a simple proxy server in Go is straightforward due to its robust standard library and support for network programming. In this article, we will guide you step by step through creating a basic HTTP proxy server using the Go programming language.

Prerequisites

  • Go installed on your system. You can download it from the official website.
  • A basic understanding of Go programming.
  • A text editor or IDE for writing your Go code.

Step 1: Set up your Go project

First, open your terminal and create a new directory for your Go project. You can name it whatever you like. Then, navigate to that directory and initialize a new Go module:

$ mkdir simple-proxy
$ cd simple-proxy
$ go mod init simple-proxy

Step 2: Write the Proxy Server Code

Next, create a new Go file, proxy.go, in the same directory, and open it in your preferred text editor. Begin by importing the necessary packages:

package main

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

Now, let's configure the handler function that will handle the incoming HTTP requests and forward them to the target server:

func handler(w http.ResponseWriter, r *http.Request) {
    // Create a new HTTP request using the method and URL from the original request
    req, err := http.NewRequest(r.Method, "http://example.com"+r.RequestURI, r.Body)
    if err != nil {
        log.Println(err)
        http.Error(w, "Server error", http.StatusInternalServerError)
        return
    }

    // Copy headers from the original request to the new request
    req.Header = r.Header

    // Send the request using an HTTP client
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Println(err)
        http.Error(w, "Server error", http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()

    // Copy headers from the response to the writer headers
    for key, values := range resp.Header {
        for _, value := range values {
            w.Header().Add(key, value)
        }
    }

    // Write the HTTP status from the response to the writer
    w.WriteHeader(resp.StatusCode)

    // Copy the response body to the writer
    io.Copy(w, resp.Body)
}

Then, within the main function, set up the server to listen on the desired port and link the handler:

func main() {
    http.HandleFunc("/", handler)
    log.Println("Starting proxy server on :8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatalf("Could not start server: %s\n", err)
    }
}

Step 3: Run your Proxy Server

Save your file and return to the terminal. Run your proxy server by executing:

$ go run proxy.go

Your server will start and listen on port 8080.

Conclusion

Congratulations! You've set up a basic proxy server using Go. This simple setup will forward all requests it receives to http://example.com. You can modify the proxy logic to suit your needs, such as managing different endpoints or adding advanced logging.

Next Article: How to set timeout when sending HTTP requests in Go

Previous Article: How to send emails using Go

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