Skip to content

Instantly share code, notes, and snippets.

@electrofocus
Created January 5, 2024 12:21
Show Gist options
  • Save electrofocus/39d80ba23dcdf8d4ec7c75019a2210cb to your computer and use it in GitHub Desktop.
Save electrofocus/39d80ba23dcdf8d4ec7c75019a2210cb to your computer and use it in GitHub Desktop.
Go Proxy Handler
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