How to Build a Simple Proxy in Go

Web
Build a simple Go proxy using httputil.NewSingleHostReverseProxy to forward HTTP requests to a target URL.

You build a simple proxy in Go by creating an http.Server with a custom http.Transport that routes requests through your target server.

package main

import (
	"context"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	target, _ := url.Parse("https://example.com")
	proxy := httputil.NewSingleHostReverseProxy(target)
	
	// Optional: Customize transport for timeouts or TLS
	proxy.Transport = &http.Transport{}

	go func() {
		if err := http.ListenAndServe(":8080", proxy); err != nil {
			panic(err)
		}
	}()

	// Keep server running
	select {}
}

Run the server with go run main.go and access it at http://localhost:8080.