Skip to content

Instantly share code, notes, and snippets.

@rahulvramesh
Forked from thurt/revprox.go
Created May 12, 2021 16:00
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 rahulvramesh/82311b075ba2d99d29d6d783e3eb5c5e to your computer and use it in GitHub Desktop.
Save rahulvramesh/82311b075ba2d99d29d6d783e3eb5c5e to your computer and use it in GitHub Desktop.
Simple reverse proxy in Go (forked from original to use a struct instead of a closure)
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)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
// use http.Handle instead of http.HandleFunc when your struct implements http.Handler interface
http.Handle("/", &ProxyHandler{proxy})
err = http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
type ProxyHandler struct {
p *httputil.ReverseProxy
}
func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
w.Header().Set("X-Ben", "Rad")
ph.p.ServeHTTP(w, r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment