From 8ac589d44e2278b547dd38a4f619316d02928b72 Mon Sep 17 00:00:00 2001 From: a Date: Fri, 8 Jul 2022 00:55:20 -0500 Subject: [PATCH] fix forwarding --- app/main.go | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/app/main.go b/app/main.go index cb753cc..7f776c4 100644 --- a/app/main.go +++ b/app/main.go @@ -5,6 +5,8 @@ import ( "log" "net" "net/http" + "net/url" + "path" "strings" "gfx.cafe/open/gun" @@ -13,6 +15,8 @@ import ( var Config struct { Port string Root string + + Remote string } func init() { @@ -21,8 +25,13 @@ func init() { Config.Port = "8080" } if Config.Root == "" { - Config.Root = "./dist" + Config.Root = "dist" } + if Config.Remote == "" { + Config.Remote = "https://beta.lifeto.co" + } + + Config.Root = path.Clean(Config.Root) } var hopHeaders = []string{ @@ -58,25 +67,34 @@ func delHopHeaders(header http.Header) { } type Handler struct { - c http.Client + p ProxyHandler } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(strings.TrimPrefix("/", r.URL.Path), "lifeto") { - h.handleProxy(w, r) + if strings.HasPrefix(r.URL.Path, "/lifeto") { + http.StripPrefix("/lifeto", &h.p).ServeHTTP(w, r) return } - h.handleProxy(w, r) + h.handleSite(w, r) } -func (h *Handler) handleProxy(w http.ResponseWriter, r *http.Request) { + +type ProxyHandler struct { + c http.Client +} + +func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { r.RequestURI = "" if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { appendHostToXForwardHeader(r.Header, clientIP) } + r.URL, _ = url.Parse(Config.Remote + r.URL.Path) + r.Host = r.URL.Host + resp, err := h.c.Do(r) if err != nil { http.Error(w, "Server Error", http.StatusInternalServerError) log.Println("ServeHTTP:", err) + return } defer resp.Body.Close() delHopHeaders(resp.Header) @@ -86,7 +104,7 @@ func (h *Handler) handleProxy(w http.ResponseWriter, r *http.Request) { } func (h *Handler) handleSite(w http.ResponseWriter, r *http.Request) { - http.StripPrefix(Config.Root, http.FileServer(http.Dir(Config.Root))).ServeHTTP(w, r) + http.FileServer(http.Dir(Config.Root)).ServeHTTP(w, r) } func main() {