Last active
January 17, 2021 15:37
-
-
Save montanaflynn/304aa58b188f036204af to your computer and use it in GitHub Desktop.
Golang reverse proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This was helpful!!
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) { ... }
}))
}
Can we reverse proxy a https connection?
👍 "Can we reverse proxy a https connection?" .. I would also like to know.
@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.
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
There's no reason to create a ReverseProxy on every request. Is there?