fix forwarding

This commit is contained in:
a 2022-07-08 00:55:20 -05:00
parent 554c5e1d33
commit 8ac589d44e
1 changed files with 25 additions and 7 deletions

View File

@ -5,6 +5,8 @@ import (
"log" "log"
"net" "net"
"net/http" "net/http"
"net/url"
"path"
"strings" "strings"
"gfx.cafe/open/gun" "gfx.cafe/open/gun"
@ -13,6 +15,8 @@ import (
var Config struct { var Config struct {
Port string Port string
Root string Root string
Remote string
} }
func init() { func init() {
@ -21,8 +25,13 @@ func init() {
Config.Port = "8080" Config.Port = "8080"
} }
if Config.Root == "" { 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{ var hopHeaders = []string{
@ -58,25 +67,34 @@ func delHopHeaders(header http.Header) {
} }
type Handler struct { type Handler struct {
c http.Client p ProxyHandler
} }
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(strings.TrimPrefix("/", r.URL.Path), "lifeto") { if strings.HasPrefix(r.URL.Path, "/lifeto") {
h.handleProxy(w, r) http.StripPrefix("/lifeto", &h.p).ServeHTTP(w, r)
return 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 = "" r.RequestURI = ""
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
appendHostToXForwardHeader(r.Header, clientIP) appendHostToXForwardHeader(r.Header, clientIP)
} }
r.URL, _ = url.Parse(Config.Remote + r.URL.Path)
r.Host = r.URL.Host
resp, err := h.c.Do(r) resp, err := h.c.Do(r)
if err != nil { if err != nil {
http.Error(w, "Server Error", http.StatusInternalServerError) http.Error(w, "Server Error", http.StatusInternalServerError)
log.Println("ServeHTTP:", err) log.Println("ServeHTTP:", err)
return
} }
defer resp.Body.Close() defer resp.Body.Close()
delHopHeaders(resp.Header) 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) { 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() { func main() {