package prxy import ( "fmt" "log" "net" "net/http" "net/http/httputil" "net/url" "github.com/xlgmokha/x/pkg/x" ) func New(routes map[string]string) http.Handler { mapped := map[string]*url.URL{} for source, destination := range routes { mapped[source] = x.Must(url.Parse(destination)) } return &httputil.ReverseProxy{ Director: func(r *http.Request) { host, _, err := net.SplitHostPort(r.Host) if err != nil { fmt.Printf("%v\n", err) return } destination := mapped[host] r.URL.Scheme = destination.Scheme r.Host = destination.Host r.URL.Host = destination.Host }, Transport: http.DefaultTransport, FlushInterval: -1, ErrorLog: nil, ModifyResponse: func(r *http.Response) error { r.Header.Add("Via", fmt.Sprintf("%v gtwy", r.Proto)) return nil }, ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { log.Println(err) }, } }