Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active January 17, 2021 15:37
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save montanaflynn/304aa58b188f036204af to your computer and use it in GitHub Desktop.
Save montanaflynn/304aa58b188f036204af to your computer and use it in GitHub Desktop.
Golang reverse proxy
package main
import (
"log"
"net/http"
"net/http/httputil"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
director := func(req *http.Request) {
req = r
req.URL.Scheme = "http"
req.URL.Host = r.Host
}
proxy := &httputil.ReverseProxy{Director: director}
proxy.ServeHTTP(w, r)
})
log.Fatal(http.ListenAndServe(":8181", nil))
}
@matryer
Copy link

matryer commented May 26, 2015

There's no reason to create a ReverseProxy on every request. Is there?

@elico
Copy link

elico commented Aug 10, 2015

This was helpful!!

@dthtvwls
Copy link

dthtvwls commented Oct 8, 2015

No, there's not. All this plumbing is already part of ReverseProxy. It could be rewritten as:

func main() {
    log.Fatal(http.ListenAndServe(":8181", &httputil.ReverseProxy{
        Director: func(r *http.Request) { ... }
    }))
}

@arun0009
Copy link

Can we reverse proxy a https connection?

@sylnsr
Copy link

sylnsr commented Mar 3, 2016

👍 "Can we reverse proxy a https connection?" .. I would also like to know.

@mrcrilly
Copy link

@arun0009 - yes. You would setup a custom listener with all the relevant TLS configuration. When you configure the httputil.ReverseProxy, you use an HTTP scheme and thus you're essentially doing TLS off-loading.

@dotqi
Copy link

dotqi commented Sep 9, 2018

How can I catch 502 errors and rewrite errors? Thank you

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