lifeto-shop/app/main.go

114 lines
2.1 KiB
Go
Raw Normal View History

2022-07-08 05:20:57 +00:00
package main
import (
"io"
"log"
"net"
"net/http"
2022-07-08 05:55:20 +00:00
"net/url"
"path"
2022-07-08 05:20:57 +00:00
"strings"
"gfx.cafe/open/gun"
)
var Config struct {
Port string
Root string
2022-07-08 05:55:20 +00:00
Remote string
2022-07-08 05:20:57 +00:00
}
func init() {
gun.Load(&Config)
if Config.Port == "" {
Config.Port = "8080"
}
if Config.Root == "" {
2022-07-08 05:55:20 +00:00
Config.Root = "dist"
}
if Config.Remote == "" {
Config.Remote = "https://beta.lifeto.co"
2022-07-08 05:20:57 +00:00
}
2022-07-08 05:55:20 +00:00
Config.Root = path.Clean(Config.Root)
2022-07-08 05:20:57 +00:00
}
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te",
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
func appendHostToXForwardHeader(header http.Header, host string) {
if prior, ok := header["X-Forwarded-For"]; ok {
host = strings.Join(prior, ", ") + ", " + host
}
header.Set("X-Forwarded-For", host)
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func delHopHeaders(header http.Header) {
for _, h := range hopHeaders {
header.Del(h)
}
}
type Handler struct {
2022-07-08 05:55:20 +00:00
p ProxyHandler
2022-07-08 05:20:57 +00:00
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2022-07-08 05:55:20 +00:00
if strings.HasPrefix(r.URL.Path, "/lifeto") {
http.StripPrefix("/lifeto", &h.p).ServeHTTP(w, r)
2022-07-08 05:20:57 +00:00
return
}
2022-07-08 05:55:20 +00:00
h.handleSite(w, r)
}
type ProxyHandler struct {
c http.Client
2022-07-08 05:20:57 +00:00
}
2022-07-08 05:55:20 +00:00
func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2022-07-08 05:20:57 +00:00
r.RequestURI = ""
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
appendHostToXForwardHeader(r.Header, clientIP)
}
2022-07-08 05:55:20 +00:00
r.URL, _ = url.Parse(Config.Remote + r.URL.Path)
r.Host = r.URL.Host
2022-07-08 05:20:57 +00:00
resp, err := h.c.Do(r)
if err != nil {
http.Error(w, "Server Error", http.StatusInternalServerError)
log.Println("ServeHTTP:", err)
2022-07-08 05:55:20 +00:00
return
2022-07-08 05:20:57 +00:00
}
defer resp.Body.Close()
delHopHeaders(resp.Header)
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func (h *Handler) handleSite(w http.ResponseWriter, r *http.Request) {
2022-07-08 05:55:20 +00:00
http.FileServer(http.Dir(Config.Root)).ServeHTTP(w, r)
2022-07-08 05:20:57 +00:00
}
func main() {
2022-07-08 05:22:00 +00:00
log.Printf("starting with config: %+v", Config)
2022-07-08 05:20:57 +00:00
http.ListenAndServe(":"+Config.Port, &Handler{})
}