Skip to content

Instantly share code, notes, and snippets.

@habibiefaried
Last active June 16, 2024 09:23
Show Gist options
  • Save habibiefaried/b14034d763c31d89a3fb2c929bc5faf5 to your computer and use it in GitHub Desktop.
Save habibiefaried/b14034d763c31d89a3fb2c929bc5faf5 to your computer and use it in GitHub Desktop.
Reverse proxy golang with oxy/forward package
package main
import (
"crypto/tls"
"github.com/vulcand/oxy/v2/forward"
"log"
"net/http"
"net/url"
)
func main() {
target := "https://reddit.com"
fwd := forward.New(true)
fwd.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// Parse the target URL
targetURL, err := url.Parse(target)
if err != nil {
log.Fatalf("Failed to parse target URL: %v", err)
}
redirect := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Create a new URL based on the original request URL
proxyURL := *targetURL
proxyURL.Path = req.URL.Path
proxyURL.RawQuery = req.URL.RawQuery
// Update the request URL to point to the target backend
req.URL = &proxyURL
// Ensure the Host header is set correctly for the target backend
req.Host = targetURL.Host
// Forward all headers from the incoming request to the target
for key, values := range req.Header {
for _, value := range values {
req.Header.Set(key, value)
}
}
// Forward the request to the backend
fwd.ServeHTTP(w, req)
})
s := &http.Server{
Addr: ":8080",
Handler: redirect,
}
s.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment