forked from a/lifeto-shop
fix forwarding
This commit is contained in:
parent
554c5e1d33
commit
8ac589d44e
32
app/main.go
32
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() {
|
||||
|
|
Loading…
Reference in New Issue