Skip to content

Instantly share code, notes, and snippets.

@dabernathy89
Created February 7, 2024 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dabernathy89/736c40d01b04da27840f90c1e8143c11 to your computer and use it in GitHub Desktop.
Save dabernathy89/736c40d01b04da27840f90c1e8143c11 to your computer and use it in GitHub Desktop.
Super simple Go reverse proxy
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
)
func main() {
// Define the outgoing URL where requests will be forwarded
outgoingURL, err := url.Parse("http://example.com") // Replace with your desired outgoing URL
if err != nil {
panic(err)
}
// Create a reverse proxy that forwards requests to the outgoing URL
proxy := httputil.NewSingleHostReverseProxy(outgoingURL)
// Handler function to handle incoming requests
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Modify the request Host header to match the outgoing URL
r.Host = outgoingURL.Host
// Serve the request using the reverse proxy
proxy.ServeHTTP(w, r)
})
// Start the server on 127.0.0.1:8080
addr := "127.0.0.1:8080"
fmt.Printf("Proxy server is running on http://%s\n", addr)
if err := http.ListenAndServe(addr, nil); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment