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-proxyStep 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.goYour 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.