Skip to content

Instantly share code, notes, and snippets.

@JalfResi
Last active June 18, 2024 18:29
Show Gist options
  • Save JalfResi/6287706 to your computer and use it in GitHub Desktop.
Save JalfResi/6287706 to your computer and use it in GitHub Desktop.
Simple reverse proxy in Go
package main
import(
"log"
"net/url"
"net/http"
"net/http/httputil"
)
func main() {
remote, err := url.Parse("http://google.com")
if err != nil {
panic(err)
}
handler := func(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
r.Host = remote.Host
w.Header().Set("X-Ben", "Rad")
p.ServeHTTP(w, r)
}
}
proxy := httputil.NewSingleHostReverseProxy(remote)
http.HandleFunc("/", handler(proxy))
err = http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
@c0d3kid
Copy link

c0d3kid commented Dec 22, 2022

Made some changes to add support for ssl. And cleanup handler.

`package main

import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"crypto/tls"
)

func main() {
// Replace 'target' with the URL of the server you want to proxy to
target, err := url.Parse("https://example.com")
if err != nil {
panic(err)
}

// Create a new ReverseProxy instance
proxy := httputil.NewSingleHostReverseProxy(target)
// Configure the reverse proxy to use HTTPS
proxy.Transport = &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// Create a handler function that logs the URL and forwards the request to the proxy
handler := func(w http.ResponseWriter, r *http.Request) {
    log.Println(r.URL)
    r.Host = target.Host
	//w.Header().Set("X-Ben", "radi")
    proxy.ServeHTTP(w, r)
}

// Register the handler function with the HTTP server
http.HandleFunc("/", handler)

// Start the HTTP server
err = http.ListenAndServe(":3000", nil)
if err != nil {
    panic(err)
}

}`

@c0d3kid
Copy link

c0d3kid commented Dec 22, 2022

@rjp
Copy link

rjp commented May 24, 2024

Helpful, ta, used this to transparently adjust some query parameters for certain requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment