Created
January 5, 2024 12:21
-
-
Save electrofocus/39d80ba23dcdf8d4ec7c75019a2210cb to your computer and use it in GitHub Desktop.
Go Proxy Handler
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 ( | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"strings" | |
) | |
func Proxy(toAddr string) http.HandlerFunc { | |
addr, err := url.Parse(toAddr) | |
if err != nil { | |
panic(err) | |
} | |
proxy := httputil.NewSingleHostReverseProxy(addr) | |
parentDirector := proxy.Director | |
// Extend director behavior to solve an issue with trailing slash. | |
// Read more here: https://github.com/golang/go/issues/50337 | |
proxy.Director = func(r *http.Request) { | |
parentDirector(r) | |
if !strings.HasSuffix(toAddr, "/") { | |
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/") | |
} | |
} | |
return func(w http.ResponseWriter, r *http.Request) { | |
r.URL = &url.URL{} | |
r.Host = addr.Host | |
proxy.ServeHTTP(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment