Simple Reverse Proxy Program in Go
Go offers a lot of functionality with the net/http package.
Go offers a lot of functionality with networking out of the box. A reverse proxy in Go can be implemented using the net/http
package, which provides a solid foundation for creating HTTP servers and clients. Here is a simple program to help proxy requests to a hard coded upstream server.
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
)
// Define a struct to hold the reverse proxy configuration
type ProxyConfig struct {
Target *url.URL
}
// ReverseProxyHandler creates a new reverse proxy handler
func ReverseProxyHandler(target *url.URL) http.Handler {
return httputil.NewSingleHostReverseProxy(target)
}
func main() {
// Define the target URL of the upstream server
targetURL := "http://localhost:8081"
target, err := url.Parse(targetURL)
if err != nil {
fmt.Println("Error parsing target URL:", err)
return
}
// Create a new reverse proxy instance
proxy := ReverseProxyHandler(target)
// Create a new HTTP server
server := &http.Server{
Addr: ":80", // Port to listen on
Handler: proxy,
}
fmt.Println("Reverse proxy server is listening on port 8080...")
// Start the HTTP server
err = server.ListenAndServe()
if err != nil {
fmt.Println("Error starting server:", err)
}
}